sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function resolveCommands($commands)
{
$commands = is_array($commands) ? $commands : func_get_args();
foreach ($commands as $command) {
$this->resolve($command);
}
} | Resolve an array of commands through the application.
@param array|mixed $commands
@return void | entailment |
public function command($signature, Closure $callback)
{
$command = new ClosureCommand($signature, $callback);
return $this->add($command);
} | Register a Closure based command with the application.
@param string $signature
@param Closure $callback
@return \Nova\Console\ClosureCommand | entailment |
public function fetch($scratchDir, LoggerInterface $logger)
{
$logger->info(sprintf('Syncing files from: %s', $this->source));
$process = ProcessBuilder::create($this->options)
->setTimeout($this->timeout)
->setPrefix('rsync')
->add($this->source)
->add($scratchDir)
->getProcess();
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
} | {@inheritdoc} | entailment |
protected function createPdoStatement($query, $pdo = null)
{
if (is_null($pdo)) {
$pdo = $this->getPdo();
}
$grammar = $this->getQueryGrammar();
$query = preg_replace_callback('#\{(.*?)\}#', function ($matches) use ($grammar)
{
$value = $matches[1];
return $grammar->wrap($value);
}, $query);
return $pdo->prepare($query);
} | Parse and wrap the variables from query, then return a propared PDO Statement instance.
@param string $query
@param \PDO $pdo
@return \PDOStatement | entailment |
public function statement($query, $bindings = array())
{
return $this->run($query, $bindings, function ($me, $query, $bindings)
{
if ($me->pretending()) return true;
$bindings = $me->prepareBindings($bindings);
//
$statement = $me->createPdoStatement($query);
return $statement->execute($bindings);
});
} | Execute an SQL statement and return the boolean result.
@param string $query
@param array $bindings
@return bool | entailment |
public function affectingStatement($query, $bindings = array())
{
return $this->run($query, $bindings, function ($me, $query, $bindings)
{
if ($me->pretending()) return 0;
$bindings = $me->prepareBindings($bindings);
//
$statement = $me->createPdoStatement($query);
$statement->execute($bindings);
return $statement->rowCount();
});
} | Run an SQL statement and get the number of rows affected.
@param string $query
@param array $bindings
@return int | entailment |
public function beginTransaction()
{
++$this->transactions;
if ($this->transactions == 1) {
$this->pdo->beginTransaction();
}
$this->fireConnectionEvent('beganTransaction');
} | Start a new database transaction.
@return void | entailment |
public function commit()
{
if ($this->transactions == 1) $this->pdo->commit();
--$this->transactions;
$this->fireConnectionEvent('committed');
} | Commit the active database transaction.
@return void | entailment |
protected function run($query, $bindings, Closure $callback)
{
$this->reconnectIfMissingConnection();
$start = microtime(true);
try {
$result = $this->runQueryCallback($query, $bindings, $callback);
}
catch (QueryException $e) {
$result = $this->tryAgainIfCausedByLostConnection(
$e, $query, $bindings, $callback
);
}
$time = $this->getElapsedTime($start);
$this->logQuery($query, $bindings, $time);
return $result;
} | Run a SQL statement and log its execution context.
@param string $query
@param array $bindings
@param \Closure $callback
@return mixed
@throws \Database\QueryException | entailment |
public function logQuery($query, $bindings, $time = null)
{
if (isset($this->events)) {
$this->events->dispatch('nova.query', array($query, $bindings, $time, $this->getName()));
}
if (! $this->loggingQueries) return;
$this->queryLog[] = compact('query', 'bindings', 'time');
} | Log a query in the connection's query log.
@param string $query
@param array $bindings
@param float|null $time
@return void | entailment |
protected function fireConnectionEvent($event)
{
if (isset($this->events)) {
$this->events->dispatch('connection.'.$this->getName().'.'.$event, $this);
}
} | Fire an event for this connection.
@param string $event
@return void | entailment |
public function getDoctrineConnection()
{
$driver = $this->getDoctrineDriver();
$data = array('pdo' => $this->pdo, 'dbname' => $this->getConfig('database'));
return new DoctrineConnection($data, $driver);
} | Get the Doctrine DBAL database connection instance.
@return \Doctrine\DBAL\Connection | entailment |
public function getCacheManager()
{
if ($this->cache instanceof Closure) {
$this->cache = call_user_func($this->cache);
}
return $this->cache;
} | Get the cache manager instance.
@return \Nova\Cache\CacheManager | entailment |
protected function buildJsonAttributes(array $map): array
{
$result = [];
foreach ($map as $jsonKey => $value) {
if ($value !== null) {
$result[$jsonKey] = $value;
}
}
return $result;
} | @param array $map
@return array | entailment |
public function register()
{
$this->registerPresenceVerifier();
$this->app->bindShared('validator', function($app)
{
$config = $app['config'];
// Get a Validation Factory instance.
$validator = new Factory($config);
if (isset($app['validation.presence'])) {
$presenceVerifier = $app['validation.presence'];
$validator->setPresenceVerifier($presenceVerifier);
}
return $validator;
});
} | Register the Service Provider.
@return void | entailment |
protected function recreateJob($delay)
{
$payload = json_decode($this->job->body, true);
array_set($payload, 'attempts', array_get($payload, 'attempts', 1) + 1);
$this->iron->recreate(json_encode($payload), $this->getQueue(), $delay);
} | Release a pushed job back onto the queue.
@param int $delay
@return void | entailment |
public function handle()
{
$this->info('Gathering Information of Roles');
$permissions = app(Role::class)->pluck(config('artify.permissions_column'))->collapse();
if (!count($permissions)) {
return $this->error('Roles are not set yet, or maybe they are not an array.');
}
if (config('artify.adr.enabled')) {
if (!count(config('artify.adr.domains'))) {
return $this->error('You should fill up the domains key inside config/artify.php with the domains you wish to register authorization for.');
}
$domains = collect(config('artify.adr.domains'))->mapToDictionary(function($domain) use($permissions){
return [
$domain => $permissions->filter(function($value, $permission) use($domain) {
return str_contains($permission, strtolower(str_singular($domain)));
})
];
});
foreach ($domains as $domain => $domainPermissions) {
if (!is_dir(app_path($domain)) || !$domainPermissions[0]->count()) {
continue;
}
$this->preparePermissions($domainPermissions[0]);
$this->currentDomain = $domain;
$this->qualifyClass();
}
}else {
$this->preparePermissions($permissions);
$this->qualifyClass();
}
} | Execute the console command.
@return mixed | entailment |
public function boot() {
Filesystem::macro('getFileName', function ($name) {
return array_last(explode('\\', $name));
});
Filesystem::macro('getNamespaceFromLocation', function ($location) {
return ucfirst(str_replace('/', '\\', $location));
});
Filesystem::macro('transformNamespaceToLocation', function ($location) {
$location = str_replace('\\', '/', $location);
$filename = array_last(explode('/', $location));
return str_replace('/' . $filename, '', $location);
});
$this->app->singleton(Manager::class, function () {
return new Manager();
});
$this->app->when(DatabaseAdapter::class)->needs('$connection')->give(config('database.default'));
$this->app->singleton(DatabaseFactory::class, function () {
return new DatabaseFactory(app(DatabaseAdapter::class));
});
$this->app->singleton(DatabaseManager::class, function () {
return new DatabaseManager(app(BaseDatabaseManager::class), app(DatabaseFactory::class));
});
\Event::listen(TenantIdentified::class, RegisterTenant::class);
} | Bootstrap services.
@return void | entailment |
public function register() {
if ($this->app->runningInConsole()) {
$this->registerConsoleCommands();
$this->app->singleton(DatabaseMigrationCommand::class, function ($app) {
return new DatabaseMigrationCommand($app->make('migrator'), $app->make(DatabaseManager::class));
});
$this->app->singleton(DatabaseRollbackCommand::class, function ($app) {
return new DatabaseRollbackCommand($app->make('migrator'), $app->make(DatabaseManager::class));
});
$this->app->singleton(DatabaseResetCommand::class, function ($app) {
return new DatabaseResetCommand($app->make('migrator'), $app->make(DatabaseManager::class));
});
$this->app->singleton(DatabaseRefreshCommand::class, function ($app) {
return new DatabaseRefreshCommand($app->make('migrator'), $app->make(DatabaseManager::class));
});
$this->app->singleton(DatabaseFreshCommand::class, function ($app) {
return new DatabaseFreshCommand($app->make(DatabaseManager::class));
});
$this->app->singleton(DatabaseSeedCommand::class, function ($app) {
return new DatabaseSeedCommand($app->make('db'), $app->make(DatabaseManager::class));
});
}
$this->registerPublishables();
$this->registerHelpers();
} | Register services.
@return void | entailment |
public function handle(Job $job, array $data)
{
$event = unserialize($data['event']);
if (method_exists($event, 'broadcastAs')) {
$name = $event->broadcastAs();
} else {
$name = get_class($event);
}
if (! is_array($channels = $event->broadcastOn())) {
$channels = array($channels);
}
$this->broadcaster->broadcast(
$channels, $name, $this->getPayloadFromEvent($event)
);
$job->delete();
} | Handle the queued job.
@param \Nova\Queue\Job $job
@param array $data
@return void | entailment |
protected function getPayloadFromEvent($event)
{
if (method_exists($event, 'broadcastWith')) {
return $event->broadcastWith();
}
$payload = array();
//
$reflection = new ReflectionClass($event);
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
$key = $property->getName();
$value = $property->getValue($event);
$payload[$key] = $this->formatProperty($value);
}
return $payload;
} | Get the payload for the given event.
@param mixed $event
@return array | entailment |
public function share(Closure $closure)
{
return function($container) use ($closure)
{
// We'll simply declare a static variable within the Closures and if it has
// not been set we will execute the given Closures to resolve this value
// and return it back to these consumers of the method as an instance.
static $object;
if (is_null($object)) {
$object = $closure($container);
}
return $object;
};
} | Wrap a Closure such that it is shared.
@param \Closure $closure
@return \Closure | entailment |
public function extend($abstract, Closure $closure)
{
if (! isset($this->bindings[$abstract])) {
throw new \InvalidArgumentException("Type {$abstract} is not bound.");
}
if (isset($this->instances[$abstract])) {
$this->instances[$abstract] = $closure($this->instances[$abstract], $this);
$this->rebound($abstract);
} else {
$extender = $this->getExtender($abstract, $closure);
$this->bind($abstract, $extender, $this->isShared($abstract));
}
} | "Extend" an abstract type in the container.
@param string $abstract
@param \Closure $closure
@return void
@throws \InvalidArgumentException | entailment |
protected function getExtender($abstract, Closure $closure)
{
// To "extend" a binding, we will grab the old "resolver" Closure and pass it
// into a new one. The old resolver will be called first and the result is
// handed off to the "new" resolver, along with this container instance.
$resolver = $this->bindings[$abstract]['concrete'];
return function($container) use ($resolver, $closure)
{
return $closure($resolver($container), $container);
};
} | Get an extender Closure for resolving a type.
@param string $abstract
@param \Closure $closure
@return \Closure | entailment |
public function wrap(Closure $callback, array $parameters = array())
{
return function () use ($callback, $parameters) {
return $this->call($callback, $parameters);
};
} | Wrap the given closure such that its dependencies will be injected when executed.
@param \Closure $callback
@param array $parameters
@return \Closure | entailment |
public function call($callback, array $parameters = array(), $defaultMethod = null)
{
if ($this->isCallableWithAtSign($callback) || $defaultMethod) {
return $this->callClass($callback, $parameters, $defaultMethod);
}
$dependencies = $this->getMethodDependencies($callback, $parameters);
return call_user_func_array($callback, $dependencies);
} | Call the given Closure / class@method and inject its dependencies.
@param callable|string $callback
@param array $parameters
@param string|null $defaultMethod
@return mixed | entailment |
public function afterResolving($abstract, Closure $callback = null)
{
if ($abstract instanceof Closure && $callback === null) {
$this->afterResolvingCallback($abstract);
} else {
$this->afterResolvingCallbacks[$abstract][] = $callback;
}
} | Register a new after resolving callback for all types.
@param string $abstract
@param \Closure|null $callback
@return void | entailment |
protected function resolvingCallback(Closure $callback)
{
$abstract = $this->getFunctionHint($callback);
if ($abstract) {
$this->resolvingCallbacks[$abstract][] = $callback;
} else {
$this->globalResolvingCallbacks[] = $callback;
}
} | Register a new resolving callback by type of its first argument.
@param \Closure $callback
@return void | entailment |
protected function afterResolvingCallback(Closure $callback)
{
$abstract = $this->getFunctionHint($callback);
if ($abstract) {
$this->afterResolvingCallbacks[$abstract][] = $callback;
} else {
$this->globalAfterResolvingCallbacks[] = $callback;
}
} | Register a new after resolving callback by type of its first argument.
@param \Closure $callback
@return void | entailment |
protected function getFunctionHint(Closure $callback)
{
$function = new ReflectionFunction($callback);
if ($function->getNumberOfParameters() == 0) {
return;
}
$expected = $function->getParameters()[0];
if (! $expected->getClass()) {
return;
}
return $expected->getClass()->name;
} | Get the type hint for this closure's first argument.
@param \Closure $callback
@return mixed | entailment |
protected function fireResolvingCallbacks($abstract, $object)
{
if (isset($this->resolvingCallbacks[$abstract])) {
$this->fireCallbackArray($object, $this->resolvingCallbacks[$abstract]);
}
$this->fireCallbackArray($object, $this->globalResolvingCallbacks);
} | Fire all of the resolving callbacks.
@param string $abstract
@param mixed $object
@return void | entailment |
protected function fireCallbackArray($object, array $callbacks)
{
foreach ($callbacks as $callback) {
call_user_func($callback, $object, $this);
}
} | Fire an array of callbacks with an object.
@param mixed $object
@param array $callbacks | entailment |
public function isShared($abstract)
{
if (isset($this->bindings[$abstract]['shared'])) {
$shared = $this->bindings[$abstract]['shared'];
} else {
$shared = false;
}
return isset($this->instances[$abstract]) || $shared === true;
} | Determine if a given type is shared.
@param string $abstract
@return bool | entailment |
public function getParams(): array
{
$params = [
'chat_id' => $this->chatId,
'phone_number' => $this->phoneNumber,
'first_name' => $this->firstName,
];
if ($this->lastName) {
$params['last_name'] = $this->lastName;
}
if ($this->disableNotification !== null) {
$params['disable_notification'] = (int)$this->disableNotification;
}
if ($this->replyToMessageId) {
$params['reply_to_message_id'] = $this->replyToMessageId;
}
return $params;
} | Get parameters for HTTP query.
@return mixed | entailment |
public function getParams(): array
{
$params = [
'chat_id' => $this->chatId,
'from_chat_id' => $this->fromChatId,
'message_id' => $this->messageId
];
if ($this->disableNotification) {
$params['disable_notification'] = (int)$this->disableNotification;
}
return $params;
} | Get parameters for HTTP query.
@return mixed | entailment |
public function get($name)
{
if (!isset($this->profiles[$name])) {
throw new \InvalidArgumentException(sprintf('Profile "%s" is not registered.', $name));
}
return $this->profiles[$name];
} | @param string $name
@return Profile | entailment |
public static function plural($value, $count = 2)
{
if (($count === 1) || static::uncountable($value)) {
return $value;
}
$plural = Inflector::pluralize($value);
return static::matchCase($plural, $value);
} | Get the plural form of an English word.
@param string $value
@param int $count
@return string | entailment |
public function addConstraints()
{
$parentTable = $this->parent->getTable();
$this->setJoin();
if (static::$constraints) {
$this->query->where($parentTable.'.'.$this->firstKey, '=', $this->farParent->getKey());
}
} | Set the base constraints on the relation query.
@return void | entailment |
protected function setJoin(Builder $query = null)
{
$query = $query ?: $this->query;
$foreignKey = $this->related->getTable().'.'.$this->secondKey;
$query->join($this->parent->getTable(), $this->getQualifiedParentKeyName(), '=', $foreignKey);
} | Set the join clause on the query.
@param \Nova\Database\ORM\Builder|null $query
@return void | entailment |
public function handleException($exception)
{
if (! $exception instanceof Exception) {
$exception = new FatalThrowableError($exception);
}
$this->getExceptionHandler()->report($exception);
if ($this->app->runningInConsole()) {
$this->renderForConsole($exception);
} else {
$this->renderHttpResponse($exception);
}
} | Handle an exception for the application.
@param \Exception $exception
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function renderForConsole($e, ConsoleOutput $output = null)
{
if (is_null($output)) {
$output = new ConsoleOutput();
}
$this->getExceptionHandler()->renderForConsole($output, $e);
} | Render an exception to the console.
@param \Exception $e
@return void | entailment |
protected function parseNamespacedSegments($key)
{
list($namespace, $item) = explode('::', $key);
// If the namespace is registered as a package, we will just assume the group
// is equal to the namespace since all packages cascade in this way having
// a single file per package, otherwise we'll just parse them as normal.
if (array_key_exists($namespace, $this->packages)) {
return $this->parsePackageSegments($key, $namespace, $item);
}
return parent::parseNamespacedSegments($key);
} | Parse an array of namespaced segments.
@param string $key
@return array | entailment |
public function handle()
{
$table = $this->container['config']['queue.connections.database.table'];
$tableClassName = Str::studly($table);
$fullPath = $this->createBaseMigration($table);
$stubPath = __DIR__ .DS . 'stubs' .DS .'jobs.stub';
$stub = str_replace(
['{{table}}', '{{tableClassName}}'], [$table, $tableClassName], $this->files->get($stubPath)
);
$this->files->put($fullPath, $stub);
$this->info('Migration created successfully!');
} | Execute the console command.
@return void | entailment |
public function create($type, $options = array(), $content = array(), $segment_opts = array(), $type_opts = array()) {
if (!in_array($type, array("regular", "plaintext", "absplit", "rss", "auto"))) {
throw new \Exception('the Campaign Type has to be one of "regular", "plaintext", "absplit", "rss", "auto" ');
}
$payload = array(
'type' => $type,
'options' => $options,
'content' => $content,
'segment_opts' => $segment_opts,
'type_opts' => $type_opts
);
$apiCall = 'campaigns/create';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return isset($data) ? $data : false;
} | Create a new draft campaign to send. You can not have more than 32,000 campaigns in your account.
@link http://apidocs.mailchimp.com/api/2.0/campaigns/create.php
@param string $type the Campaign Type has to be one of "regular", "plaintext", "absplit", "rss", "auto"
@param array $options
@param array $content
@param array $segment_opts
@param array $type_opts
@return array Campaign data
@throws \Exception
@throws MailchimpAPIException | entailment |
public function content($options = array()) {
$payload = array(
'cid' => $this->cid,
'options' => $options
);
$apiCall = 'campaigns/content';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return isset($data) ? $data : false;
} | Get the content (both html and text) for a campaign either as it would appear in the campaign archive or as the raw, original content
@link http://apidocs.mailchimp.com/api/2.0/campaigns/content.php
@param array $options
@return array Campaign content
@throws MailchimpAPIException | entailment |
public function get($filters = array(), $start = 0, $limit = 25, $sort_field = 'create_time', $sort_dir = "DESC") {
if (!in_array(strtolower($sort_field), array("create_time", "send_time", "title", "subject")))
throw new \Exception('sort_field has to be one of "create_time", "send_time", "title", "subject" ');
if (!in_array(strtoupper($sort_dir), array("ASC", "DESC")))
throw new \Exception('sort_dir has to be one of "ASC", "DESC" ');
$payload = array(
'filters' => $filters,
'start' => $start,
'limit' => $limit,
'sort_field' => $sort_field,
'sort_dir' => $sort_dir
);
$apiCall = 'campaigns/list';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return isset($data) ? $data : false;
} | Get the list of campaigns and their details matching the specified filters
@link http://apidocs.mailchimp.com/api/2.0/campaigns/list.php
@param array $filters
@param int $start start page
@param int $limit limit
@param string $sort_field
@param string $sort_dir
@return array
@throws \Exception
@throws MailchimpAPIException | entailment |
public function del() {
$payload = array(
'cid' => $this->cid
);
$apiCall = 'campaigns/delete';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return true;
} | Delete a campaign. Seriously, "poof, gone!" - be careful! Seriously, no one can undelete these.
@link http://apidocs.mailchimp.com/api/2.0/campaigns/delete.php
@return boolean
@throws MailchimpAPIException | entailment |
public function templateContent() {
$payload = array(
'cid' => $this->cid
);
$apiCall = 'campaigns/template-content';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return isset($data) ? $data : false;
} | Get the HTML template content sections for a campaign. Note that this will return very jagged,
non-standard results based on the template a campaign is using.
You only want to use this if you want to allow editing template sections in your application.
@link http://apidocs.mailchimp.com/api/2.0/campaigns/template-content.php
@return boolean true on success
@return array Campaign Template data
@throws MailchimpAPIException | entailment |
public function schedule($schedule_time, $schedule_time_b = null) {
$payload = array(
'cid' => $this->cid,
'schedule_time' => $schedule_time,
'schedule_time_b' => $schedule_time_b
);
$apiCall = 'campaigns/schedule';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return true;
} | Schedule a campaign to be sent in the future
@link http://apidocs.mailchimp.com/api/2.0/campaigns/schedule.php
@param string $schedule_time
@param string $schedule_time_b
@return boolean true on success
@throws MailchimpAPIException | entailment |
public function scheduleBatch($schedule_time, $num_batches = 2, $stagger_mins = 5) {
$payload = array(
'cid' => $this->cid,
'schedule_time' => $schedule_time,
'num_batches' => $num_batches,
'stagger_mins' => $stagger_mins
);
$apiCall = 'campaigns/schedule-batch';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return true;
} | Schedule a campaign to be sent in batches sometime in the future. Only valid for "regular" campaigns
@link http://apidocs.mailchimp.com/api/2.0/campaigns/schedule-batch.php
@param string $schedule_time
@param int $num_batches
@param int $stagger_mins
@return boolean true on success
@throws MailchimpAPIException | entailment |
public function update($name, $value) {
$payload = array(
'cid' => $this->cid,
'name' => $name,
'value' => $value
);
$apiCall = 'campaigns/update';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data, true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return true;
} | Update just about any setting besides type for a campaign that has not been sent
@link http://apidocs.mailchimp.com/api/2.0/campaigns/update.php
@param string $id the Campaign Id to update
@param string $name parameter name
@param string $value parameter value
@return boolean true on success
@throws MailchimpAPIException | entailment |
public function hasTable($table)
{
$sql = $this->grammar->compileTableExists();
$table = $this->connection->getTablePrefix().$table;
return count($this->connection->select($sql, array($table))) > 0;
} | Determine if the given table exists.
@param string $table
@return bool | entailment |
public function hasColumn($table, $column)
{
$column = strtolower($column);
return in_array($column, array_map('strtolower', $this->getColumnListing($table)));
} | Determine if the given table has a given column.
@param string $table
@param string $column
@return bool | entailment |
public function getColumnListing($table)
{
$table = $this->connection->getTablePrefix().$table;
$results = $this->connection->select($this->grammar->compileColumnExists($table));
return $this->connection->getPostProcessor()->processColumnListing($results);
} | Get the column listing for a given table.
@param string $table
@return array | entailment |
public function drop($table)
{
$blueprint = $this->createBlueprint($table);
$blueprint->drop();
$this->build($blueprint);
} | Drop a table from the schema.
@param string $table
@return \Nova\Database\Schema\Blueprint | entailment |
public function dropIfExists($table)
{
$blueprint = $this->createBlueprint($table);
$blueprint->dropIfExists();
$this->build($blueprint);
} | Drop a table from the schema if it exists.
@param string $table
@return \Nova\Database\Schema\Blueprint | entailment |
protected function createBlueprint($table, Closure $callback = null)
{
if (isset($this->resolver))
{
return call_user_func($this->resolver, $table, $callback);
}
return new Blueprint($table, $callback);
} | Create a new command set with a Closure.
@param string $table
@param \Closure $callback
@return \Nova\Database\Schema\Blueprint | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$registry = $this->getBackupHelper()->getProfileRegistry();
if (!$profile = $input->getArgument('profile')) {
$this->listProfiles($output, $registry);
return;
}
$this->doExecute($registry->get($profile), $input, $output);
} | {@inheritdoc} | entailment |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$httpHandler = $request->getAttribute(AttributeEnum::ROUTER_ATTRIBUTE);
/* @var HandlerAdapter $handlerAdapter */
$handlerAdapter = App::getBean('httpHandlerAdapter');
return $handlerAdapter->doHandler($request, $httpHandler);
} | execute action
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface
@throws \Swoft\Exception\InvalidArgumentException
@throws \Swoft\Http\Server\Exception\RouteNotFoundException
@throws \Swoft\Http\Server\Exception\MethodNotAllowedException
@throws \InvalidArgumentException
@throws \ReflectionException | entailment |
public function compileCreate(Blueprint $blueprint, Fluent $command)
{
$columns = implode(', ', $this->getColumns($blueprint));
$sql = 'create table '.$this->wrapTable($blueprint)." ($columns";
// SQLite forces primary keys to be added when the table is initially created
// so we will need to check for a primary key commands and add the columns
// to the table's declaration here so they can be created on the tables.
$sql .= (string) $this->addForeignKeys($blueprint);
$sql .= (string) $this->addPrimaryKeys($blueprint);
return $sql .= ')';
} | Compile a create table command.
@param \Nova\Database\Schema\Blueprint $blueprint
@param \Nova\Support\Fluent $command
@return string | entailment |
protected function addForeignKeys(Blueprint $blueprint)
{
$sql = '';
$foreigns = $this->getCommandsByName($blueprint, 'foreign');
// Once we have all the foreign key commands for the table creation statement
// we'll loop through each of them and add them to the create table SQL we
// are building, since SQLite needs foreign keys on the tables creation.
foreach ($foreigns as $foreign) {
$sql .= $this->getForeignKey($foreign);
if (! is_null($foreign->onDelete)) {
$sql .= " on delete {$foreign->onDelete}";
}
if (! is_null($foreign->onUpdate)) {
$sql .= " on update {$foreign->onUpdate}";
}
}
return $sql;
} | Get the foreign key syntax for a table creation statement.
@param \Nova\Database\Schema\Blueprint $blueprint
@return string|null | entailment |
protected function getForeignKey($foreign)
{
$on = $this->wrapTable($foreign->on);
// We need to columnize the columns that the foreign key is being defined for
// so that it is a properly formatted list. Once we have done this, we can
// return the foreign key SQL declaration to the calling method for use.
$columns = $this->columnize($foreign->columns);
$onColumns = $this->columnize((array) $foreign->references);
return ", foreign key($columns) references $on($onColumns)";
} | Get the SQL for the foreign key.
@param \Nova\Support\Fluent $foreign
@return string | entailment |
protected function addPrimaryKeys(Blueprint $blueprint)
{
$primary = $this->getCommandByName($blueprint, 'primary');
if (! is_null($primary)) {
$columns = $this->columnize($primary->columns);
return ", primary key ({$columns})";
}
} | Get the primary key syntax for a table creation statement.
@param \Nova\Database\Schema\Blueprint $blueprint
@return string|null | entailment |
public function handle()
{
$daemon = $this->option('daemon');
if ($this->downForMaintenance() && ! $daemon) {
return;
}
// We'll listen to the processed and failed events so we can write information
// to the console as jobs are processed, which will let the developer watch
// which jobs are coming through a queue and be informed on its progress.
$this->listenForEvents();
// Get the Config Repository instance.
$config = $this->container['config'];
$connection = $this->argument('connection') ?: $config->get('queue.default');
$delay = $this->option('delay');
// The memory limit is the amount of memory we will allow the script to occupy
// before killing it and letting a process manager restart it for us, which
// is to protect us against any memory leaks that will be in the scripts.
$memory = $this->option('memory');
// We need to get the right queue for the connection which is set in the queue
// configuration file for the application. We will pull it based on the set
// connection being run for the queue operation currently being executed.
$queue = $this->option('queue') ?: $config->get(
"queue.connections.{$connection}.queue", 'default'
);
$this->runWorker($connection, $queue, $delay, $memory, $daemon);
} | Execute the console command.
@return void | entailment |
protected function listenForEvents()
{
$events = $this->container['events'];
$events->listen('nova.queue.processing', function ($connection, $job)
{
$this->writeOutput($job, 'starting');
});
$events->listen('nova.queue.processed', function ($connection, $job)
{
$this->writeOutput($job, 'success');
});
$events->listen('nova.queue.failed', function ($connection, $job)
{
$this->writeOutput($job, 'failed');
});
} | Listen for the queue events in order to update the console output.
@return void | entailment |
protected function runWorker($connection, $queue, $delay, $memory, $daemon = false)
{
$this->worker->setDaemonExceptionHandler(
$this->container['Nova\Foundation\Exceptions\HandlerInterface']
);
$sleep = $this->option('sleep');
$tries = $this->option('tries');
if (! $daemon) {
return $this->worker->runNextJob($connection, $queue, $delay, $sleep, $tries);
}
$this->worker->setCache(
$this->container['cache']->driver()
);
return $this->worker->daemon($connection, $queue, $delay, $memory, $sleep, $tries);
} | Run the worker instance.
@param string $connection
@param string $queue
@param int $delay
@param int $memory
@param bool $daemon
@return array | entailment |
protected function writeStatus(Job $job, $status, $type)
{
$date = Carbon::now()->format('Y-m-d H:i:s');
$message = sprintf("<{$type}>[%s] %s</{$type}> %s", $date, str_pad("{$status}:", 11), $job->resolveName());
$this->output->writeln($message);
} | Format the status output for the queue worker.
@param \Illuminate\Contracts\Queue\Job $job
@param string $status
@param string $type
@return void | entailment |
public function provideSymfonyService($name, $symfonyName = null)
{
if (null === $symfonyName) {
$symfonyName = $name;
}
if (parent::offsetExists($name)) {
throw new \LogicException(sprintf('Service %s has already been defined.', $name));
}
$this->delegates[$name] = $symfonyName;
} | Provide a symfony service in this container.
@param string $name The name of the service.
@param null|string $symfonyName The name of the service in the symfony container (if not equal).
@return void
@throws \LogicException When the service being set is already contained in the DIC. | entailment |
public function offsetSet($id, $value)
{
if (isset($this->delegates[$id])) {
throw new \LogicException(sprintf('Service %s has been delegated to symfony, cannot set.', $id));
}
// @codingStandardsIgnoreStart
@trigger_error(
'get service: The pimple based DIC is deprecated, use the symfony DIC in new projects.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$this->values[$id] = $value;
} | Sets a parameter or an object.
Objects must be defined as Closures.
Allowing any PHP callable leads to difficult to debug problems
as function names (strings) are callable (creating a function with
the same a name as an existing parameter would break your container).
@param string $id The unique identifier for the parameter or object.
@param mixed $value The value of the parameter or a closure to defined an object.
@return void
@SuppressWarnings(PHPMD.ShortVariableName)
@throws \LogicException When the service being set is already delegated to the symfony DIC. | entailment |
public function offsetGet($id)
{
if (isset($this->delegates[$id])) {
// @codingStandardsIgnoreStart
@trigger_error(
sprintf(
'getting service "%1$s" via pimple based DIC is deprecated, use the symfony service "%2$s"',
$id,
$this->delegates[$id]
),
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
return $this->getSymfonyService($this->delegates[$id]);
}
// @codingStandardsIgnoreStart
@trigger_error(
'get service: The pimple based DIC is deprecated, use the symfony DIC in new projects.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
return parent::offsetGet($id);
} | Gets a parameter or an object.
@param string $id The unique identifier for the parameter or object.
@return mixed The value of the parameter or an object.
@throws \InvalidArgumentException If the identifier is not defined.
@SuppressWarnings(PHPMD.ShortVariableName) | entailment |
public function offsetExists($id)
{
if (isset($this->delegates[$id])) {
return true;
}
// @codingStandardsIgnoreStart
@trigger_error(
'isset service: The pimple based DIC is deprecated, use the symfony DIC in new projects.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
return parent::offsetExists($id);
} | Checks if a parameter or an object is set.
@param string $id The unique identifier for the parameter or object.
@return bool
@SuppressWarnings(PHPMD.ShortVariableName) | entailment |
public function offsetUnset($id)
{
if (isset($this->delegates[$id])) {
throw new \LogicException(sprintf('Service %s has been delegated to symfony, cannot unset.', $id));
}
// @codingStandardsIgnoreStart
@trigger_error(
'unset service: The pimple based DIC is deprecated, use the symfony DIC in new projects.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
parent::offsetUnset($id);
} | Unset a parameter or an object.
@param string $id The unique identifier for the parameter or object.
@return void
@throws \LogicException When the service being unset is delegated to the symfony DIC.
@SuppressWarnings(PHPMD.ShortVariableName) | entailment |
public function process(ActionInterface $action, EntryCollection $collection)
{
$users = $this->getUsers();
foreach ($users as $user) {
$collection->add(new EntryUnaware(\get_class($user[0]), $user[0]->getId()), 'SONATA_ADMIN');
}
} | {@inheritdoc} | entailment |
protected function getUsers()
{
$qb = $this->registry->getManager()->createQueryBuilder();
$qb
->select('u')
->from($this->userClass, 'u')
->where($qb->expr()->like('u.roles', ':roles'))
->setParameter('roles', '%"ROLE_SUPER_ADMIN"%');
return $qb->getQuery()->iterate();
} | Returns corresponding users.
@return \Doctrine\ORM\Internal\Hydration\IterableResult | entailment |
public function handle()
{
$pattern = storage_path('logs') .DS .'*.log';
$files = $this->files->glob($pattern);
foreach ($files as $file) {
$this->files->delete($file);
}
$this->info('Log files cleared successfully!');
} | Execute the console command.
@author Sang Nguyen | entailment |
public function getParams(): array
{
$params = [
'chat_id' => $this->chatId,
'voice' => $this->voice,
];
$params = array_merge($params, $this->buildJsonAttributes([
'duration' => $this->duration,
'disable_notification' => $this->disableNotification,
'reply_to_message_id' => $this->replyToMessageId
]));
return $params;
} | Get parameters for HTTP query.
@return mixed | entailment |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
/* @var \Swoft\Http\Server\Parser\RequestParserInterface $requestParser */
$requestParser = App::getBean('requestParser');
$request = $requestParser->parse($request);
return $handler->handle($request);
} | do process
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface | entailment |
public function registerPolicies(GateContract $gate)
{
foreach ($this->policies as $key => $value) {
$gate->policy($key, $value);
}
} | Register the application's policies.
@param \Nova\Contracts\Auth\Access\Gate $gate
@return void | entailment |
protected function registerRepository()
{
$this->app->bindShared('migration.repository', function($app)
{
$table = $app['config']['database.migrations'];
return new DatabaseMigrationRepository($app['db'], $table);
});
} | Register the migration repository service.
@return void | entailment |
protected function registerMakeCommand()
{
$this->app->bindShared('migration.creator', function($app)
{
return new MigrationCreator($app['files']);
});
$this->app->bindShared('command.migrate.make', function($app)
{
$creator = $app['migration.creator'];
$packagePath = $app['path.base'] .DS .'vendor';
return new MakeMigrationCommand($creator, $packagePath);
});
} | Register the "install" migration command.
@return void | entailment |
public function up()
{
Schema::create(config('actionlog.action_logs_table'), function (Blueprint $table) {
$table->engine = "InnoDB COMMENT='用户操作记录表'";
$table->increments('id');
$table->integer(config('actionlog.user_foreign_key'))
->unsigned()
->comment('操作者ID');
$table->string('type', 50)
->comment('操作类型');
$table->text('content')
->comment('操作描述');
$table->string('client_ip', 20)
->comment('操作者IP');
$table->string('client')
->comment('客户端信息');
$table->timestamp('created_at');
$table->index(config('actionlog.user_foreign_key'));
$table->index('type');
$table->index('created_at');
});
} | Run the migrations.
@return void | entailment |
protected function registerPackageAssets($package, $namespace, $path)
{
$assets = $path .DS .'Assets';
if ($this->app['files']->isDirectory($assets)) {
$namespace = 'modules/' .str_replace('_', '-', $namespace);
$this->app['assets.dispatcher']->package($package, $assets, $namespace);
}
} | Register the package's assets.
@param string $package
@param string $namespace
@param string $path
@return void | entailment |
public function boot()
{
$events = $this->app->make(Dispatcher::class);
$this->registerEventListeners($events);
if ($this->app->bound(Kernel::class)) {
$kernel = $this->app->make(Kernel::class);
$router = $this->app->make(Router::class);
$this->registerRouteMiddleware($router, $kernel);
$this->bootExtensionRouting();
}
$this->bootExtensionComponents();
} | {@inheritdoc} | entailment |
public function format($change = false) {
// lower case values only
$change = strtolower($change);
// if set, attempt to change format
if ($change){
switch($change){
// allowed formats, change to new format
case "xml":
case "json":
$this->format = $change;
break;
// other formats now allowed/recognised
default:
return false;
break;
}
// return the new format (string)
return $this->format;
} else {
// get and return the current format
return $this->format;
}
} | Return or change the output format (returned by VATSIM)
@param string $change json|xml
@return string current format or bool false (unable to set format) | entailment |
public function signature($signature, $private_key = false) {
$signature = strtoupper($signature);
// RSA-SHA1 public key/private key encryption
if ($signature == 'RSA' || $signature == 'RSA-SHA1') {
// private key must be provided
if (!$private_key){
return false;
}
// signature method set to RSA-SHA1 using this private key (interacts with OAuth class)
$this->signature = new RsaSha1($private_key);
return true;
} elseif ($signature == 'HMAC' || $signature == 'HMAC-SHA1') {
// signature method set to HMAC-SHA1 - no private key
$this->signature = new HmacSha1;
return true;
} else {
// signature method was not recognised
return false;
}
} | Set the signing method to be used to encrypt request signature.
@param string $signature Signature encryption method: RSA|HMAC
@param string $private_key openssl RSA private key (only needed if using RSA)
@return boolean true if able to use this signing type | entailment |
public function requestToken($return_url=false, $allow_sus=false, $allow_ina=false) {
// signature method must have been set
if (!$this->signature){
return false;
}
// if the return URL isn't specified, assume this file (though don't consider GET data)
if (!$return_url){
// using https or http?
$http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) ? 'https://' : 'http://';
// the current URL
$return_url = $http.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
}
$tokenUrl = $this->base.$this->loc_api.$this->loc_token.$this->format.'/';
// generate a token request from the consumer details
$req = Request::from_consumer_and_token($this->consumer, false, "POST", $tokenUrl, array(
'oauth_callback' => (String) $return_url,
'oauth_allow_suspended' => ($allow_sus) ? true : false,
'oauth_allow_inactive' => ($allow_ina) ? true : false
));
// sign the request using the specified signature/encryption method (set in this class)
$req->sign_request($this->signature, $this->consumer, false);
$response = $this->curlRequest($tokenUrl, $req->to_postdata());
if ($response){
// convert using our response format (depending upon user preference)
$sso = $this->responseFormat($response);
// did VATSIM return a successful result?
if ($sso->request->result == 'success'){
// this parameter is required by 1.0a spec
if ($sso->token->oauth_callback_confirmed == 'true'){
// store the token data saved
$this->token = new Consumer($sso->token->oauth_token, $sso->token->oauth_token_secret);
// return the full object to the user
return $sso;
} else {
// no callback_confirmed parameter
$this->error = array(
'type' => 'callback_confirm',
'code' => false,
'message' => 'Callback confirm flag missing - protocol mismatch'
);
return false;
}
} else {
// oauth returned a failed request, store the error details
$this->error = array(
'type' => 'oauth_response',
'code' => false,
'message' => $sso->request->message
);
return false;
}
} else {
// cURL response failed
return false;
}
} | Request a login token from VATSIM (required to send someone for an SSO login)
@param string $return_url URL for VATSIM to return memers to after login
@param boolean $allow_sus true to allow suspended VATSIM accounts to log in
@param boolean $allow_ina true to allow inactive VATSIM accounts to log in
@return object|boolean | entailment |
public function sendToVatsim() {
// a token must have been returned to redirect this user
if (!$this->token){
return false;
}
// redirect to the SSO login location, appending the token
return $this->base . $this->loc_login . $this->token->key;
} | Redirect the user to VATSIM to log in/confirm login
@return boolean false if failed | entailment |
public function checkLogin($tokenKey, $tokenSecret, $tokenVerifier) {
$this->token = new Consumer($tokenKey, $tokenSecret);
// the location to send a cURL request to to obtain this user's details
$returnUrl = $this->base.$this->loc_api.$this->loc_return.$this->format.'/';
// generate a token request call using post data
$req = Request::from_consumer_and_token($this->consumer, $this->token, "POST", $returnUrl, array(
'oauth_token' => $tokenKey,
'oauth_verifier' => $tokenVerifier
));
// sign the request using the specified signature/encryption method (set in this class)
$req->sign_request($this->signature, $this->consumer, $this->token);
// post the details to VATSIM and obtain the result
$response = $this->curlRequest($returnUrl, $req->to_postdata());
if ($response){
// convert using our response format (depending upon user preference)
$sso = $this->responseFormat($response);
// did VATSIM return a successful result?
if ($sso->request->result == 'success'){
// one time use of tokens only, token no longer valid
$this->token = false;
// return the full object to the user
return $sso;
} else {
// oauth returned a failed request, store the error details
$this->error = array(
'type' => 'oauth_response',
'code' => false,
'message' => $sso->request->message
);
return false;
}
} else {
// cURL response failed
return false;
}
} | Obtains a user's login details from a token key and secret
@param string $tokenKey The token key provided by VATSIM
@param secret $tokenSecret The secret associated with the token
@return object|false false if error, otherwise returns user details | entailment |
private function curlRequest($url, $requestString) {
// using cURL to post the request to VATSIM
$ch = curl_init();
// configure the post request to VATSIM
curl_setopt_array($ch, array(
CURLOPT_URL => $url, // the url to make the request to
CURLOPT_RETURNTRANSFER => 1, // do not output the returned data to the user
CURLOPT_TIMEOUT => $this->timeout, // time out the request after this number of seconds
CURLOPT_POST => 1, // we are sending this via post
CURLOPT_POSTFIELDS => $requestString // a query string to be posted (key1=value1&key2=value2)
));
// perform the request
$response = curl_exec($ch);
// request failed?
if (!$response){
$this->error = array(
'type' => 'curl_response',
'code' => curl_errno($ch),
'message' => curl_error($ch)
);
return false;
} else {
return $response;
}
} | Perform a (post) cURL request
@param type $url Destination of request
@param type $requestString Query string of data to be posted
@return boolean true if able to make request | entailment |
public function createDuplicateType($new_id = NULL) {
$duplicate = parent::createDuplicate();
if (!empty($new_id)) {
$duplicate->id = $new_id;
$duplicate->label = "Duplicate. " . $duplicate->label;
}
return $duplicate;
} | {@inheritdoc} | entailment |
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
if ($update) {
// Clear the cached field definitions as some settings affect the field
// definitions.
$this->entityManager()->clearCachedFieldDefinitions();
}
} | {@inheritdoc} | entailment |
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
// Clear the site_commerce type cache to reflect the removal.
$storage->resetCache(array_keys($entities));
} | {@inheritdoc} | entailment |
public function register()
{
$this->app['vatsimoauth'] = $this->app->share(function($app)
{
return new SSO(
$app['config']->get('sso::base'), // base
$app['config']->get('sso::key'), // key
$app['config']->get('sso::secret'), // secret
$app['config']->get('sso::method'), // method
$app['config']->get('sso::cert') // certificate
);
});
} | Register the service provider.
@return void | entailment |
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = [];
$element['visible'] = array(
'#type' => 'select',
'#title' => $this->t('Display field'),
'#options' => array('0' => $this->t('Disallow'), '1' => $this->t('Allow')),
'#default_value' => isset($items[$delta]->visible) ? $items[$delta]->visible : '1',
'#theme_wrappers' => [],
);
$element['unit'] = array(
'#type' => 'select',
'#title' => $this->t('Unit of measurement'),
'#options' => getUnitMeasurement(),
'#default_value' => isset($items[$delta]->unit) ? $items[$delta]->unit : null,
'#empty_value' => '',
'#theme_wrappers' => [],
);
$element['min'] = array(
'#type' => 'number',
'#title' => $this->t('Minimum order quantity'),
'#default_value' => isset($items[$delta]->min) ? $items[$delta]->min : '1',
'#empty_value' => '1',
'#step' => '1',
'#min' => '1',
'#theme_wrappers' => [],
);
$element['stock'] = array(
'#type' => 'number',
'#title' => $this->t('Quantity in stock'),
'#default_value' => isset($items[$delta]->stock) ? $items[$delta]->stock : '1',
'#empty_value' => '1',
'#step' => '1',
'#min' => '0',
'#theme_wrappers' => [],
);
$element['#theme'] = 'site_commerce_quantity_default_widget';
return $element;
} | {@inheritdoc} | entailment |
public function edit(Listener $listener)
{
$eloquent = Auth::user();
$form = $this->presenter->password($eloquent);
return $listener->showPasswordChanger(['eloquent' => $eloquent, 'form' => $form]);
} | Get password information.
@param \Orchestra\Contracts\Foundation\Listener\Account\PasswordUpdater $listener
@return mixed | entailment |
public function update(Listener $listener, array $input)
{
$user = Auth::user();
if (! $this->validateCurrentUser($user, $input)) {
return $listener->abortWhenUserMismatched();
}
$validation = $this->validator->on('changePassword')->with($input);
if ($validation->fails()) {
return $listener->updatePasswordFailedValidation($validation->getMessageBag());
}
if (! Hash::check($input['current_password'], $user->password)) {
return $listener->verifyCurrentPasswordFailed();
}
try {
$this->saving($user, $input);
} catch (Exception $e) {
return $listener->updatePasswordFailed(['error' => $e->getMessage()]);
}
return $listener->passwordUpdated();
} | Update password information.
@param \Orchestra\Contracts\Foundation\Listener\Account\PasswordUpdater $listener
@param array $input
@return mixed | entailment |
public function create(Listener $listener)
{
$eloquent = Foundation::make('orchestra.user');
$form = $this->presenter->profile($eloquent, 'orchestra::register');
$form->extend(function ($form) {
$form->submit = 'orchestra/foundation::title.register';
});
$this->fireEvent('form', [$eloquent, $form]);
return $listener->showProfileCreator(compact('eloquent', 'form'));
} | View registration page.
@param \Orchestra\Contracts\Foundation\Listener\Account\ProfileCreator $listener
@return mixed | entailment |
public function store(Listener $listener, array $input)
{
$temporaryPassword = null;
$password = $input['password'] ?? null;
if (empty($password)) {
$password = $temporaryPassword = \resolve(GenerateRandomPassword::class)();
}
$validation = $this->validator->on('register')->with($input);
// Validate user registration, if any errors is found redirect it
// back to registration page with the errors
if ($validation->fails()) {
return $listener->createProfileFailedValidation($validation->getMessageBag());
}
$user = Foundation::make('orchestra.user');
try {
$this->saving($user, $input, $password);
} catch (Exception $e) {
return $listener->createProfileFailed(['error' => $e->getMessage()]);
}
return $this->notifyCreatedUser($listener, $user, $temporaryPassword);
} | Create a new user.
@param \Orchestra\Contracts\Foundation\Listener\Account\ProfileCreator $listener
@param array $input
@return mixed | entailment |
protected function notifyCreatedUser(Listener $listener, Eloquent $user, ?string $temporaryPassword)
{
try {
$user->sendWelcomeNotification($temporaryPassword);
} catch (Exception $e) {
return $listener->profileCreatedWithoutNotification();
}
return $listener->profileCreated();
} | Send new registration e-mail to user.
@param \Orchestra\Contracts\Foundation\Listener\Account\ProfileCreator $listener
@param \Orchestra\Model\User $user
@param string|null $temporaryPassword
@return mixed | entailment |
protected function saving(Eloquent $user, array $input, $password)
{
$user->setAttribute('email', $input['email']);
$user->setAttribute('fullname', $input['fullname']);
$user->setAttribute('password', $password);
$this->fireEvent('creating', [$user]);
$this->fireEvent('saving', [$user]);
$user->saveOrFail();
$this->fireEvent('created', [$user]);
$this->fireEvent('saved', [$user]);
} | Saving new user.
@param \Orchestra\Model\User $user
@param array $input
@param string $password
@return void | entailment |
Subsets and Splits