sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getControllerMethod() { if (! isset($this->method)) { list (, $method) = $this->parseControllerCallback(); return $this->method = $method; } return $this->method; }
Get the controller method used for the route. @return string
entailment
protected function compileRoute() { if (! $this->compiled) { return $this->compiled = with(new RouteCompiler($this))->compile(); } return $this->compiled; }
Compile the route into a Symfony CompiledRoute instance. @return void
entailment
public function parameters() { if (! isset($this->parameters)) { throw new \LogicException("Route is not bound."); } return array_map(function ($value) { return is_string($value) ? rawurldecode($value) : $value; }, $this->parameters); }
Get the key / value list of parameters for the route. @return array @throws \LogicException
entailment
protected function compileParameterNames() { preg_match_all('/\{(.*?)\}/', $this->domain() .$this->uri, $matches); return array_map(function ($match) { return trim($match, '?'); }, $matches[1]); }
Get the parameter names for the route. @return array
entailment
public function bindParameters(Request $request) { // If the route has a regular expression for the host part of the URI, we will // compile that and get the parameter matches for this domain. We will then // merge them into this parameters array so that this array is completed. $params = $this->matchToKeys( array_slice($this->bindPathParameters($request), 1) ); // If the route has a regular expression for the host part of the URI, we will // compile that and get the parameter matches for this domain. We will then // merge them into this parameters array so that this array is completed. if (! is_null($this->compiled->getHostRegex())) { $params = $this->bindHostParameters($request, $params); } return $this->parameters = $this->replaceDefaults($params); }
Extract the parameter list from the request. @param \Nova\Http\Request $request @return array
entailment
protected function bindPathParameters(Request $request) { preg_match($this->compiled->getRegex(), '/' .$request->decodedPath(), $matches); return $matches; }
Get the parameter matches for the path portion of the URI. @param \Nova\Http\Request $request @return array
entailment
protected function matchToKeys(array $matches) { $parameterNames = $this->parameterNames(); if (count($parameterNames) == 0) { return array(); } $parameters = array_intersect_key($matches, array_flip($parameterNames)); return array_filter($parameters, function ($value) { return is_string($value) && (strlen($value) > 0); }); }
Combine a set of parameter matches with the route's keys. @param array $matches @return array
entailment
protected function replaceDefaults(array $parameters) { foreach ($parameters as $key => &$value) { if (! isset($value)) { $value = Arr::get($this->defaults, $key); } } return $parameters; }
Replace null parameters with their defaults. @param array $parameters @return array
entailment
public function prefix($prefix) { $this->uri = trim($prefix, '/') .'/' .trim($this->uri, '/'); return $this; }
Add a prefix to the route URI. @param string $prefix @return $this
entailment
public function process($scratchDir, Namer $namer, LoggerInterface $logger) { $filename = sprintf('%s/%s.%s', sys_get_temp_dir(), $namer->generate(), $this->extension); $logger->info(sprintf('Archiving files to: %s', $filename)); $process = ProcessBuilder::create(array($this->command, $this->options, $filename, './')) ->setWorkingDirectory($scratchDir) ->setTimeout($this->timeout) ->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } return $filename; }
{@inheritdoc}
entailment
public function cleanup($filename, LoggerInterface $logger) { $logger->info(sprintf('Deleting %s', $filename)); if (file_exists($filename)) { unlink($filename); } }
{@inheritdoc}
entailment
public function handle() { $model = $this->argument('model'); if ($this->filesystem->exists(app_path("/Http/Controllers/{$model}Controller.php"))) return $this->error("Controller already exists"); if (!$this->filesystem->exists(app_path($model.'.php'))) { $this->call('make:model', ['name' => $model]); } if (!$this->filesystem->exists(app_path('/Http/Requests/'.$model.'StoreRequestForm.php'))) { $this->call('make:request', ['name' => "{$model}StoreRequestForm"]); } if (!$this->filesystem->exists(app_path('/Http/Requests/'.$model.'UpdateRequestForm.php'))) { $this->call('make:request', ['name' => "{$model}UpdateRequestForm"]); } $defaultControllerContent = $this->filesystem->get(artify_path('artifies/stubs/DummyController.stub')); if ($this->option('repository')) { $this->call('artify:repository', ['name' => "{$model}Repository"]); $runtimeControllerContent = str_replace(['$dummy->delete();','$dummy->update(request()->all());','Dummy::latest()','Dummy::create(request()->all());'],['\DummyRepository::delete($dummy->id);','\DummyRepository::update($dummy->id, request()->all());','\DummyRepository::latest()','\DummyRepository::create(request()->all());'],$defaultControllerContent); } if (!$this->filesystem->exists(app_path('/Http/Controllers/'.$model.'Controller.php'))) { if (!config('artify.cache.enabled')) { $layerName = strpos($runtimeControllerContent ?? $defaultControllerContent, '\DummyRepository') ? '\DummyRepository' : 'Dummy'; if($this->option('repository')){ $assignedLayer = '$dummies = \\' . $model .'Repostiroy::latest()->get();'; } $runtimeControllerContent = str_replace(["cache()->forget('dummies');\n", "cache('dummies')",'cache()->remember(\'dummies\', config(\'artify.cache.duration\'), function () { $dummies = ' . $layerName . '::latest()->get(); });'], ['', '$dummies', $assignedLayer ?? '$dummies = Dummy::latest()->get();'], $runtimeControllerContent ?? $defaultControllerContent); } $runtimeControllerContent = str_replace( ['dummy', 'Dummy', 'dummies'], [strtolower($model), ucfirst($model), strtolower(str_plural($model))], $runtimeControllerContent ?? $defaultControllerContent ); $this->filesystem->put(artify_path('artifies/stubs/DummyController.stub'), $runtimeControllerContent); $this->filesystem->copy(artify_path('artifies/stubs/DummyController.stub'), app_path('/Http/Controllers/'.$model.'Controller.php')); $this->filesystem->put(artify_path('artifies/stubs/DummyController.stub'), $defaultControllerContent); $this->filesystem->append(base_path('routes/web.php'), "\nRoute::resource('" . strtolower($model) . "', '{$model}Controller');"); $this->info("{$model} crud created successfully"); } }
Execute the console command. @return mixed
entailment
public function processColumnListing($results) { return array_values(array_map(function ($result) { $result = (object) $result; return $result->column_name; }, $results)); }
Process the results of a column listing query. @param array $results @return array
entailment
public function make($value, array $options = array()) { $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds; $hash = password_hash($value, PASSWORD_DEFAULT, array('cost' => $cost)); if ($hash === false) { throw new \RuntimeException("Bcrypt hashing not supported."); } return $hash; }
Hash the given value. @param string $value @param array $options @return string @throws \RuntimeException
entailment
public function needsRehash($hashedValue, array $options = array()) { $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds; return password_needs_rehash($hashedValue, PASSWORD_DEFAULT, array('cost' => $cost)); }
Check if the given hash has been hashed using the given options. @param string $hashedValue @param array $options @return bool
entailment
public function setApiVersion($version) { if (!in_array($version, $this->availableVersions, true)) { throw new UnsupportedStripeVersionException(sprintf( 'The given Stripe version ("%s") is not supported by ZfrStripe. Value must be one of the following: "%s"', $version, implode(', ', $this->availableVersions) )); } $this->version = (string) $version; $this->setDefaultOption('headers', ['Stripe-Version' => $this->version]); if ($this->version < '2015-08-19') { $descriptor = __DIR__ . '/ServiceDescription/Stripe-v1.0.php'; } else { $descriptor = __DIR__ . '/ServiceDescription/Stripe-v1.1.php'; } // Note that we need to recreate a whole new CompositeFactory whenever the version is changed $this->setCommandFactory(new CompositeFactory()); $this->setDescription(ServiceDescription::factory($descriptor)); }
Set the Stripe API version This method forces to add a Stripe-Version header, so that you can use the wanted version no matter what the setting is on Stripe @param string $version @return void
entailment
public function afterPrepare(Event $event) { /* @var \Guzzle\Service\Command\CommandInterface $command */ $command = $event['command']; $request = $command->getRequest(); $request->getQuery()->setAggregator(new StripeQueryAggregator()); }
Modify the query aggregator @internal @param Event $event @return void
entailment
public function authorizeRequest(Event $event) { /* @var \Guzzle\Service\Command\CommandInterface $command */ $command = $event['command']; $request = $command->getRequest(); $request->setAuth($this->apiKey); }
Authorize the request @internal @param Event $event @return void
entailment
public function connection($name = null) { $name = $name ?: $this->getDefaultDriver(); // If the connection has not been resolved yet we will resolve it now as all // of the connections are resolved when they are actually needed so we do // not make any unnecessary connection to the various queue end-points. if ( ! isset($this->connections[$name])) { $this->connections[$name] = $this->resolve($name); $this->connections[$name]->setContainer($this->app); $this->connections[$name]->setEncrypter($this->app['encrypter']); } return $this->connections[$name]; }
Resolve a queue connection instance. @param string $name @return \Nova\Queue\Contracts\QueueInterface
entailment
protected function resolve($name) { $config = $this->getConfig($name); return $this->getConnector($config['driver'])->connect($config); }
Resolve a queue connection. @param string $name @return \Nova\Queue\Contracts\QueueInterface
entailment
protected function getConnector($driver) { if (isset($this->connectors[$driver])) { return call_user_func($this->connectors[$driver]); } throw new \InvalidArgumentException("No connector for [$driver]"); }
Get the connector for a given driver. @param string $driver @return \Nova\Queue\Contracts\ConnectorInterface @throws \InvalidArgumentException
entailment
public function handle(EventInterface $event) { // header获取日志ID和spanid请求跨度ID $logid = RequestContext::getRequest()->getHeaderLine('logid'); $spanid = RequestContext::getRequest()->getHeaderLine('spanid'); if (empty($logid)) { $logid = uniqid(); } if (empty($spanid)) { $spanid = 0; } $uri = RequestContext::getRequest()->getUri(); $contextData = [ 'logid' => $logid, 'spanid' => $spanid, 'uri' => $uri, 'requestTime' => microtime(true), ]; RequestContext::setContextData($contextData); }
事件回调 @param EventInterface $event 事件对象
entailment
public function register() { $me = $this; $this->app->bindShared('mailer', function($app) use ($me) { $me->registerSwiftMailer(); // Once we have create the mailer instance, we will set a container instance // on the mailer. This allows us to resolve mailer classes via containers // for maximum testability on said classes instead of passing Closures. $mailer = new Mailer( $app['view'], $app['swift.mailer'], $app['events'] ); $this->setMailerDependencies($mailer, $app); // If a "from" address is set, we will set it on the mailer so that all mail // messages sent by the applications will utilize the same "from" address // on each one, which makes the developer's life a lot more convenient. $from = $app['config']['mail.from']; if (is_array($from) && isset($from['address'])) { $mailer->alwaysFrom($from['address'], $from['name']); } // Here we will determine if the mailer should be in "pretend" mode for this // environment, which will simply write out e-mail to the logs instead of // sending it over the web, which is useful for local dev environments. $pretend = $app['config']->get('mail.pretend', false); $mailer->pretend($pretend); return $mailer; }); }
Register the service provider. @return void
entailment
protected function setMailerDependencies($mailer, $app) { $mailer->setContainer($app); if ($app->bound('log')) { $mailer->setLogger($app['log']); } if ($app->bound('queue')) { $mailer->setQueue($app['queue']); } }
Set a few dependencies on the mailer instance. @param \Nova\Mail\Mailer $mailer @param \Nova\Foundation\Application $app @return void
entailment
protected function registerSwiftTransport($config) { $this->app['swift.transport'] = $this->app->share(function($app) { return new TransportManager($app); }); }
Register the Swift Transport instance. @param array $config @return void @throws \InvalidArgumentException
entailment
public function showAction($slug) { $securityContext = $this->container->get('security.authorization_checker'); $question = $this->getQuestionRepository()->findOneBySlug($slug); if (!$question || (!$question->isPublic() && !$securityContext->isGranted('ROLE_EDITOR'))) { throw $this->createNotFoundException('question not found'); } return $this->render( 'GenjFaqBundle:Question:show.html.twig', array( 'question' => $question ) ); }
shows question if active @param string $slug @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException @return \Symfony\Component\HttpFoundation\Response
entailment
public function listMostRecentAction($max = 3) { $questions = $this->getQuestionRepository()->retrieveMostRecent($max); return $this->render( 'GenjFaqBundle:Question:list_most_recent.html.twig', array( 'questions' => $questions, 'max' => $max ) ); }
list most recent added questions based on publishAt @param int $max @return \Symfony\Component\HttpFoundation\Response
entailment
public function listByQueryAction($query, $max = 30, $whereFields = array('headline', 'body')) { $questions = $this->getQuestionRepository()->retrieveByQuery($query, $max, $whereFields); return $this->render( 'GenjFaqBundle:Question:list_by_query.html.twig', array( 'questions' => $questions, 'max' => $max ) ); }
list questions which fitting the query @param string $query @param int $max @param array $whereFields @return \Symfony\Component\HttpFoundation\Response
entailment
public function teaserByIdOrObjectAction($id = null, $object = null, $style = null, $source = null, $headline = null) { $question = $object; if ($id !== null) { $question = $this->getQuestionRepository()->findOneById($id); } return $this->render( 'GenjFaqBundle:Question:teaser_by_id_or_object.html.twig', array( 'question' => $question, 'style' => $style, 'source' => $source, 'headline' => $headline ) ); }
@param int $id @param \stdClass $object @param string $style @param string $source @param string $headline @return \Symfony\Component\HttpFoundation\Response
entailment
public function load(Application $app, array $providers) { $manifest = $this->loadManifest(); // First we will load the service manifest, which contains information on all // service providers registered with the application and which services it // provides. This is used to know which services are "deferred" loaders. if ($this->shouldRecompile($manifest, $providers)) { $manifest = $this->compileManifest($app, $providers); } // If the application is running in the console, we will not lazy load any of // the service providers. This is mainly because it's not as necessary for // performance and also so any provided Artisan commands get registered. if ($app->runningInConsole()) { $manifest['eager'] = $manifest['providers']; } // Next, we will register events to load the providers for each of the events // that it has requested. This allows the service provider to defer itself // while still getting automatically loaded when a certain event occurs. foreach ($manifest['when'] as $provider => $events) { $this->registerLoadEvents($app, $provider, $events); } // We will go ahead and register all of the eagerly loaded providers with the // application so their services can be registered with the application as // a provided service. Then we will set the deferred service list on it. foreach ($manifest['eager'] as $provider) { $app->register($this->createProvider($app, $provider)); } $app->setDeferredServices($manifest['deferred']); }
Register the application service providers. @param \Nova\Foundation\Application $app @param array $providers @return void
entailment
public function writeManifest($manifest) { $content = "<?php\n\nreturn " .var_export($manifest, true) .";\n"; $this->files->put($this->manifestPath, $content); return array_merge(array('when' => array()), $manifest); }
Write the service manifest file to disk. @param array $manifest @return array
entailment
protected function getMessage($e) { $path = last($this->lastCompiled); return $e->getMessage() .' (View: ' .realpath($path) .')'; }
Get the exception message for an exception. @param \Exception $e @return string
entailment
public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $client = $this->getHttpClient(); $client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', [ 'body' => [ 'key' => $this->key, 'raw_message' => (string) $message, 'async' => false, ], ]); }
{@inheritdoc}
entailment
public function report(Exception $e) { if ($this->shouldReport($e)) { $this->event->fire(new ExceptionEvent($e)); } parent::report($e); }
Report or log an exception. This is a great spot to send exceptions to Sentry, Bugsnag, etc. In this implementation, we just send an Event though. @param \Exception $e @return void
entailment
public function render($request, Exception $exception) { $exception = $this->prepareException($exception); if ($exception instanceof HttpResponseException) { return $exception->getResponse(); } elseif ($exception instanceof AuthenticationException) { return $this->unauthenticated($request, $exception); } elseif ($exception instanceof ValidationException) { return $this->convertValidationExceptionToResponse($exception, $request); } elseif ($this->isHttpException($exception) && $this->customErrorHtmlTemplateExists($exception)) { return $this->prepareResponse($request, $exception); } $flattened = FlattenException::create($exception); $code = $flattened->getStatusCode(); $headers = $flattened->getHeaders(); $response = $this->getContent($exception, $code, $request); // If it's already a response, return that. if (!$response instanceof BaseResponse) { $response = new Response($this->getContent($exception, $code, $request), $code, $headers); } return $response; }
Render an exception into an HTTP response. @param \Illuminate\Http\Request $request @param \Exception $exception @return Response|BaseResponse
entailment
protected function getContent(Exception $exception, $code, Request $request) { // Only if the debug mode is enabled, show a more verbose error message. if ((boolean)$this->config->get('app.debug') === true) { if (class_exists(Whoops::class)) { // If Whoops is loaded, use the DebugDisplay class. return $this->app->make(DebugDisplay::class)->setRequest($request)->display($exception, $code); } else { // Fall back to the default Laravel error response. return $this->toIlluminateResponse($this->convertExceptionToResponse($exception), $exception); } } // For production/non-debug environments, use the PlainDisplay class. return $this->app->make(PlainDisplay::class)->setRequest($request)->display($exception, $code); }
Get the HTML content associated with the given exception. @param \Exception $exception @param int $code @param \Illuminate\Http\Request $request @return string
entailment
public function setUrl(string $url = null) { $this->url = $url; if ($url !== null) { $this->callbackData = null; $this->switchInlineQuery = null; } return $this; }
@param null|string $url @return InlineKeyboardButton
entailment
public function setSwitchInlineQuery(string $switchInlineQuery = null) { $this->switchInlineQuery = $switchInlineQuery; if ($switchInlineQuery !== null) { $this->callbackData = null; $this->url = null; } return $this; }
@param null|string $switchInlineQuery @return InlineKeyboardButton
entailment
public function setCallbackData($callbackData) { $this->callbackData = $callbackData; if ($callbackData !== null) { $this->url = null; $this->switchInlineQuery = null; } return $this; }
@param null|string $callbackData @return InlineKeyboardButton
entailment
public function jsonSerialize() { $result = [ 'text' => $this->text ]; if ($this->url !== null) { $result['url'] = $this->url; } elseif ($this->callbackData !== null) { $result['callback_data'] = $this->callbackData; } elseif ($this->switchInlineQuery !== null) { $result['switch_inline_query'] = $this->switchInlineQuery; } else { throw new \LogicException("InlineKeyboardButton serialize error: url or callback_data or switch_inline_query must be set"); } $result = array_merge($result, $this->buildJsonAttributes([ 'switch_inline_query_current_chat' => $this->switchInlineQueryCurrentChat ])); return $result; }
Specify data which should be serialized to JSON
entailment
public function previous() { $referrer = $this->request->headers->get('referer'); $url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession(); return $url ?: $this->to('/'); }
Get the URL for the previous request. @return string
entailment
protected function removeIndex($root) { $index = 'index.php'; return Str::contains($root, $index) ? str_replace('/' .$index, '', $root) : $root; }
Remove the index.php file from a path. @param string $root @return string
entailment
protected function getScheme($secure) { if (is_null($secure)) { return $this->forceSchema ?: $this->request->getScheme() .'://'; } return $secure ? 'https://' : 'http://'; }
Get the scheme for a raw URL. @param bool|null $secure @return string
entailment
protected function toRoute($route, array $parameters, $absolute) { $domain = $this->getRouteDomain($route, $parameters); $root = $this->replaceRoot($route, $domain, $parameters); $uri = strtr(rawurlencode($this->trimUrl( $root, $this->replaceRouteParameters($route->uri(), $parameters) )), $this->dontEncode) .$this->getRouteQueryString($parameters); return $absolute ? $uri : '/' .ltrim(str_replace($root, '', $uri), '/'); }
Get the URL for a given route instance. @param \Nova\Routing\Route $route @param array $parameters @param bool $absolute @return string
entailment
protected function replaceRoot($route, $domain, &$parameters) { return $this->replaceRouteParameters($this->getRouteRoot($route, $domain), $parameters); }
Replace the parameters on the root path. @param \Nova\Routing\Route $route @param string $domain @param array $parameters @return string
entailment
protected function replaceRouteParameters($path, array &$parameters) { if (count($parameters) > 0) { $path = preg_replace_sub( '/\{.*?\}/', $parameters, $this->replaceNamedParameters($path, $parameters) ); } return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); }
Replace all of the wildcard parameters for a route path. @param string $path @param array $parameters @return string
entailment
protected function replaceNamedParameters($path, &$parameters) { return preg_replace_callback('/\{(.*?)\??\}/', function ($match) use (&$parameters) { return isset($parameters[$match[1]]) ? Arr::pull($parameters, $match[1]) : $match[0]; }, $path); }
Replace all of the named parameters in the path. @param string $path @param array $parameters @return string
entailment
protected function getRouteDomain($route, &$parameters) { return $route->domain() ? $this->formatDomain($route, $parameters) : null; }
Get the formatted domain for a given route. @param \Nova\Routing\Route $route @param array $parameters @return string
entailment
protected function addPortToDomain($domain) { if (in_array($this->request->getPort(), array('80', '443'))) { return $domain; } return $domain .':' .$this->request->getPort(); }
Add the port to the domain if necessary. @param string $domain @return string
entailment
public function action($action, $parameters = array(), $absolute = true) { return $this->route($action, $parameters, $absolute, $this->routes->getByAction($action)); }
Get the URL to a controller action. @param string $action @param mixed $parameters @param bool $absolute @return string
entailment
public function getParams(): array { $params = [ 'chat_id' => $this->chatId ]; if ($this->parseMode) { $params['parse_mode'] = $this->parseMode; } if ($this->disableWebPagePreview) { $params['disable_web_page_preview'] = (int)$this->disableWebPagePreview; } 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
function jsonSerialize() { $data = [ 'text' => $this->text ]; if ($this->replyMarkup) { $data['reply_markup'] = $this->replyMarkup; } return $data; }
Specify data which should be serialized to JSON @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource. @since 5.4.0
entailment
public function handle() { $path = base_path('shared'); if ($this->files->exists($path)) { $this->error('The Shared namespace already exists!'); return false; } $steps = array( 'Generating folders...' => 'generateFolders', 'Generating files...' => 'generateFiles', 'Updating the composer.json ...' => 'updateComposerJson', ); $progress = new ProgressBar($this->output, count($steps)); $progress->start(); foreach ($steps as $message => $method) { $progress->setMessage($message); call_user_func(array($this, $method), $path); $progress->advance(); } $progress->finish(); $this->info("\nGenerating optimized class loader"); $this->container['composer']->dumpOptimized(); $this->info("Package generated successfully."); }
Execute the console command. @return mixed
entailment
protected function generateFolders($path) { if (! $this->files->isDirectory($path)) { $this->files->makeDirectory($path, 0755, true, true); } $this->files->makeDirectory($path .DS .'Language'); $this->files->makeDirectory($path .DS .'Support'); // Generate the Language folders. $languages = $this->container['config']->get('languages', array()); foreach (array_keys($languages) as $code) { $directory = $path .DS .'Language' .DS .strtoupper($code); $this->files->makeDirectory($directory); } }
Generate the folders. @param string $type @return void
entailment
protected function generateFiles($path) { // // Generate the custom helpers file. $content ='<?php //---------------------------------------------------------------------- // Custom Helpers //---------------------------------------------------------------------- '; $filePath = $path .DS .'Support' .DS .'helpers.php'; $this->files->put($filePath, $content); // // Generate the Language files. $content ='<?php return array ( );'; $languages = $this->container['config']->get('languages', array()); foreach (array_keys($languages) as $code) { $filePath = $path .DS .'Language' .DS .strtoupper($code) .DS .'messages.php'; $this->files->put($filePath, $content); } }
Generate the files. @param string $type @return void
entailment
protected function updateComposerJson($path) { $helpers = 'shared/Support/helpers.php'; // $composerJson = getenv('COMPOSER') ?: 'composer.json'; $path = base_path($composerJson); // Get the composer.json contents in a decoded form. $config = json_decode(file_get_contents($path), true); if (! is_array($config)) { return; } // Update the composer.json else if (! in_array($helpers, $files = Arr::get($config, "autoload.files", array()))) { array_push($files, $helpers); Arr::set($config, "autoload.files", $files); $output = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; file_put_contents($path, $output); } }
Update the composer.json and run the Composer. @param string $type @return void
entailment
public function generate() { $dateTime = new \DateTime('now', $this->timezone); return $this->prefix.$dateTime->format($this->format); }
{@inheritdoc}
entailment
public function user() { if ($this->loggedOut) { return; } // If we have already retrieved the user for the current request we can just // return it back immediately. We do not want to pull the user data every // request into the method because that would tremendously slow an app. if (! is_null($this->user)) { return $this->user; } $id = $this->session->get($this->getName()); // First we will try to load the user using the identifier in the session if // one exists. Otherwise we will check for a "remember me" cookie in this // request, and if one exists, attempt to retrieve the user using that. $user = null; if (! is_null($id)) { $user = $this->provider->retrieveByID($id); } // If the user is null, but we decrypt a "recaller" cookie we can attempt to // pull the user data on that cookie which serves as a remember cookie on // the application. Once we have a user we can return it to the caller. $recaller = $this->getRecaller(); if (is_null($user) && ! is_null($recaller)) { $user = $this->getUserByRecaller($recaller); } return $this->user = $user; }
Get the currently authenticated user. @return \Nova\Auth\UserInterface|null
entailment
public function id() { if ($this->loggedOut) { return; } $id = $this->session->get($this->getName(), $this->getRecallerId()); if (is_null($id) && ! is_null($user = $this->user())) { $id = $user->getAuthIdentifier(); } return $id; }
Get the ID for the currently authenticated user. @return int|null
entailment
protected function getUserByRecaller($recaller) { if ($this->validRecaller($recaller) && ! $this->tokenRetrievalAttempted) { $this->tokenRetrievalAttempted = true; list($id, $token) = explode('|', $recaller, 2); $this->viaRemember = ! is_null($user = $this->provider->retrieveByToken($id, $token)); return $user; } }
Pull a user from the repository by its recaller ID. @param string $recaller @return mixed
entailment
protected function getRecallerId() { if ($this->validRecaller($recaller = $this->getRecaller())) { $segments = explode('|', $recaller); return head($segments); } }
Get the user ID from the recaller cookie. @return string
entailment
protected function validRecaller($recaller) { if (! is_string($recaller) || ! str_contains($recaller, '|')) { return false; } $segments = explode('|', $recaller); return (count($segments) == 2) && (trim($segments[0]) !== '') && (trim($segments[1]) !== ''); }
Determine if the recaller cookie is in a valid format. @param string $recaller @return bool
entailment
public function basic($field = 'email', Request $request = null) { if ($this->check()) { return; } $request = $request ?: $this->getRequest(); // If a username is set on the HTTP basic request, we will return out without // interrupting the request lifecycle. Otherwise, we'll need to generate a // request indicating that the given credentials were invalid for login. if ($this->attemptBasic($request, $field)) { return; } return $this->getBasicResponse(); }
Attempt to authenticate using HTTP Basic Auth. @param string $field @param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response|null
entailment
public function onceBasic($field = 'email', Request $request = null) { $request = $request ?: $this->getRequest(); if (! $this->once($this->getBasicCredentials($request, $field))) { return $this->getBasicResponse(); } }
Perform a stateless HTTP Basic login attempt. @param string $field @param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response|null
entailment
protected function fireAttemptEvent(array $credentials, $remember, $login) { if ($this->events) { $payload = array($credentials, $remember, $login); $this->events->dispatch('auth.attempt', $payload); } }
Fire the attempt event with the arguments. @param array $credentials @param bool $remember @param bool $login @return void
entailment
public function login(UserInterface $user, $remember = false) { $this->updateSession($user->getAuthIdentifier()); // If the user should be permanently "remembered" by the application we will // queue a permanent cookie that contains the encrypted copy of the user // identifier. We will then decrypt this later to retrieve the users. if ($remember) { $this->createRememberTokenIfDoesntExist($user); $this->queueRecallerCookie($user); } // If we have an event dispatcher instance set we will fire an event so that // any listeners will hook into the authentication events and run actions // based on the login and logout events fired from the guard instances. if (isset($this->events)) { $this->events->dispatch('auth.login', array($user, $remember)); } $this->setUser($user); }
Log a user into the application. @param \Auth\UserInterface $user @param bool $remember @return void
entailment
public function loginUsingId($id, $remember = false) { $this->session->put($this->getName(), $id); $user = $this->provider->retrieveById($id); $this->login($user, $remember); return $user; }
Log the given user ID into the application. @param mixed $id @param bool $remember @return \Nova\Auth\UserInterface
entailment
public function onceUsingId($id) { $user = $this->provider->retrieveById($id); $this->setUser($user); return ($user instanceof UserInterface); }
Log the given user ID into the application without sessions or cookies. @param mixed $id @return bool
entailment
protected function queueRecallerCookie(UserInterface $user) { $value = $user->getAuthIdentifier() .'|' .$user->getRememberToken(); $cookie = $this->createRecaller($value); $this->getCookieJar()->queue($cookie); }
Queue the recaller cookie into the cookie jar. @param \Auth\UserInterface $user @return void
entailment
protected function createRecaller($value) { $cookies = $this->getCookieJar(); return $cookies->forever($this->getRecallerName(), $value); }
Create a remember me cookie for a given ID. @param string $value @return \Symfony\Component\HttpFoundation\Cookie
entailment
protected function refreshRememberToken(UserInterface $user) { $user->setRememberToken($token = str_random(60)); $this->provider->updateRememberToken($user, $token); }
Refresh the remember token for the user. @param \Auth\UserInterface $user @return void
entailment
protected function createRememberTokenIfDoesntExist(UserInterface $user) { $rememberToken = $user->getRememberToken(); if (empty($rememberToken)) { $this->refreshRememberToken($user); } }
Create a new remember token for the user if one doesn't already exist. @param \Auth\UserInterface $user @return void
entailment
public function setUser(UserInterface $user) { $this->user = $user; $this->loggedOut = false; return $this; }
Set the current user of the application. @param \Auth\UserInterface $user @return void
entailment
public function compile() { $route = $this->getRoute(); // $optionals = $this->extractOptionalParameters($uri = $route->uri()); $path = preg_replace('/\{(\w+?)\?\}/', '{$1}', $uri); $domain = $route->domain() ?: ''; return with( new SymfonyRoute($path, $optionals, $route->patterns(), array(), $domain) )->compile(); }
Compile the route. @return \Symfony\Component\Routing\CompiledRoute
entailment
protected function extractOptionalParameters($uri) { preg_match_all('/\{(\w+?)\?\}/', $uri, $matches); return isset($matches[1]) ? array_fill_keys($matches[1], null) : array(); }
Get the optional parameters for the route. @param string $uri @return array
entailment
protected function getForge() { if (isset($this->forge)) { return $this->forge; } $this->app->loadDeferredProviders(); $this->forge = ConsoleApplication::make($this->app); return $this->forge->boot(); }
Get the forge console instance. @return \Nova\Console\Application
entailment
public function load(ObjectManager $manager) { $data = array( 'category-subscription' => array( 'How can I get a subscription?', 'When will my subscription renew?', 'When will I receive the bill for my subscription?', 'How do I cancel my subscription?', 'This question exists in both categories' ), 'category-website' => array( 'I lost my password', 'I cannot log in to the website', 'I have a cool idea for the website', 'This question exists in both categories' ) ); $rank = 0; foreach ($data as $category => $questions) { foreach ($questions as $questionText) { $question = new Question(); $question->setHeadline($questionText); $question->setBody('The answer to the question "' . $questionText . '".'); $question->setRank($rank); $question->setCategory($this->getReference($category)); $question->setIsActive(true); $question->setPublishAt(new \DateTime(date('Y-m-d H:i:s', (time() - rand(1, 200))))); $manager->persist($question); $rank++; } } $manager->flush(); }
{@inheritDoc}
entailment
public function handle() { list($path, $contents) = $this->getKeyFile(); $key = $this->getRandomKey(); $contents = str_replace($this->container['config']['app.key'], $key, $contents); $this->files->put($path, $contents); $this->container['config']['app.key'] = $key; $this->info("Application key [$key] set successfully."); }
Execute the console command. @return void
entailment
protected function getKeyFile() { $path = $this->container['path'] .DS .'Config' .DS .'App.php'; $contents = $this->files->get($path); return array($path, $contents); }
Get the key file and contents. @return array
entailment
public function on($first, $operator, $second, $boolean = 'and', $where = false) { $this->clauses[] = compact('first', 'operator', 'second', 'boolean', 'where'); if ($where) $this->bindings[] = $second; return $this; }
Add an "on" clause to the join. @param string $first @param string $operator @param string $second @param string $boolean @param bool $where @return $this
entailment
public function where($first, $operator, $second, $boolean = 'and') { return $this->on($first, $operator, $second, $boolean, true); }
Add an "on where" clause to the join. @param string $first @param string $operator @param string $second @param string $boolean @return \Nova\Database\Query\JoinClause
entailment
public function setDefaultPathAndDomain($path, $domain) { list($this->path, $this->domain) = array($path, $domain); return $this; }
Set the default path and domain for the jar. @param string $path @param string $domain @return self
entailment
public function handle() { $failed = $this->container['queue.failer']->find($this->argument('id')); if ( ! is_null($failed)) { $failed->payload = $this->resetAttempts($failed->payload); $this->container['queue']->connection($failed->connection)->pushRaw($failed->payload, $failed->queue); $this->container['queue.failer']->forget($failed->id); $this->info('The failed job has been pushed back onto the queue!'); } else { $this->error('No failed job matches the given ID.'); } }
Execute the console command. @return void
entailment
public function report(Exception $e) { if ($this->shouldntReport($e)) { return; } if (method_exists($e, 'report')) { return $e->report(); } try { $logger = $this->container->make(LoggerInterface::class); } catch (Exception $ex) { throw $e; // Throw the original exception } $logger->error($e); }
Report or log an exception. @param \Exception $e @return void
entailment
protected function prepareException(Exception $e) { if ($e instanceof ModelNotFoundException) { $e = new NotFoundHttpException($e->getMessage(), $e); } else if ($e instanceof AuthorizationException) { $e = new HttpException(403, $e->getMessage()); } return $e; }
Prepare exception for rendering. @param \Exception $e @return \Exception
entailment
public function render(Request $request, Exception $e) { $e = $this->prepareException($e); if ($e instanceof HttpResponseException) { return $e->getResponse(); } else if ($e instanceof AuthenticationException) { return $this->unauthenticated($request, $e); } else if ($e instanceof ValidationException) { return $this->convertValidationExceptionToResponse($e, $request); } return $this->prepareResponse($request, $e); }
Render an exception into a response. @param \Nova\Http\Request $request @param \Exception $e @return \Nova\Http\Response
entailment
protected function prepareResponse(Request $request, Exception $e) { if ($this->isHttpException($e)) { return $this->createResponse($this->renderHttpException($e, $request), $e); } else { return $this->createResponse($this->convertExceptionToResponse($e, $request), $e); } }
Prepare response containing exception render. @param \Nova\Http\Request $request @param \Exception $e @return \Symfony\Component\HttpFoundation\Response
entailment
protected function createResponse($response, Exception $e) { $response = new HttpResponse($response->getContent(), $response->getStatusCode(), $response->headers->all()); return $response->withException($e); }
Map exception into a Nova response. @param \Symfony\Component\HttpFoundation\Response $response @param \Exception $e @return \Nova\Http\Response
entailment
protected function convertValidationExceptionToResponse(ValidationException $e, Request $request) { if ($e->response) { return $e->response; } $errors = $e->validator->errors()->getMessages(); if ($request->ajax() || $request->wantsJson()) { return Response::json($errors, 422); } return Redirect::back()->withInput($request->input())->withErrors($errors); }
Create a response object from the given validation exception. @param \Nova\Validation\ValidationException $e @param \Nova\Http\Request $request @return \Symfony\Component\HttpFoundation\Response
entailment
protected function convertExceptionToResponse(Exception $e, Request $request) { $debug = Config::get('app.debug'); // $e = FlattenException::create($e); $handler = new SymfonyExceptionHandler($debug); return SymfonyResponse::create($handler->getHtml($e), $e->getStatusCode(), $e->getHeaders()); }
Convert the given exception into a Response instance. @param \Exception $e @return \Symfony\Component\HttpFoundation\Response
entailment
public function connect(array $config) { $options = $this->getOptions($config); if ($config['database'] == ':memory:') { return $this->createConnection('sqlite::memory:', $config, $options); } $path = realpath($config['database']); if ($path === false) { throw new \InvalidArgumentException("Database does not exist."); } return $this->createConnection("sqlite:{$path}", $config, $options); }
Establish a database connection. @param array $config @return \PDO @throws \InvalidArgumentException
entailment
public function send(Swift_Mime_Message $message, &$failedRecipients = null) { return $this->ses->sendRawEmail([ 'Source' => $message->getSender(), 'Destinations' => $this->getTo($message), 'RawMessage' => [ 'Data' => base64_encode((string) $message), ], ]); }
{@inheritdoc}
entailment
protected function getTo(Swift_Mime_Message $message) { $destinations = []; $contacts = array_merge( (array) $message->getTo(), (array) $message->getCc(), (array) $message->getBcc() ); foreach ($contacts as $address => $display) { $destinations[] = $address; } return $destinations; }
Get the "to" payload field for the API request. @param \Swift_Mime_Message $message @return array
entailment
public function generateLink(ComponentInterface $component, ActionInterface $action = null) { if (!$this->pool) { return $component->getHash(); } $admin = $this->getAdmin($component, $action); if (!$admin) { return $component->getHash(); } foreach (['edit', 'show'] as $mode) { if ($admin->hasRoute($mode) && $admin->isGranted(strtoupper($mode))) { return sprintf( '<a href="%s">%s</a>', $admin->generateObjectUrl($mode, $component->getData()), $admin->toString($component->getData()) ); } } return $admin->toString($component->getData()); }
@param ComponentInterface $component @param ActionInterface|null $action @return string
entailment
protected function getAdmin(ComponentInterface $component, ActionInterface $action = null) { if ($action && $adminComponent = $action->getComponent('admin_code')) { return $this->pool->getAdminByAdminCode($adminComponent); } try { return $this->pool->getAdminByClass($component->getModel()); } catch (\RuntimeException $e) { } return false; }
@param ComponentInterface $component @param ActionInterface|null $action @return AdminInterface
entailment
protected function buildClass($name) { $stub = parent::buildClass($name); $event = $this->option('event'); // $namespace = $this->container->getNamespace(); if (! Str::startsWith($event, $namespace)) { $event = $namespace .'Events\\' .$event; } $stub = str_replace( '{{event}}', class_basename($event), $stub ); $stub = str_replace( '{{fullEvent}}', $event, $stub ); return $stub; }
Build the class with the given name. @param string $name @return string
entailment
public static function info(LogInfo $info) { $log = new ActionLogModel(); if (!$info->getUserId() && !config('actionlog.guest')) { return false; } $content = $info->getContent(); $client = $info->getClient(); $userKey = config('actionlog.user_foreign_key'); $log->$userKey = $info->getUserId(); $log->type = $info->getType(); $log->content = is_string($content) ? $content : json_encode($content); $log->client_ip = $info->getClientIp(); $log->client = is_string($client) ? $client : json_encode($client); $log->created_at = Carbon::now(); $log->save(); return true; }
Logging Action @param \Sco\ActionLog\LogInfo $info @return bool
entailment
public function validAuthenticationResponse(Request $request, $result) { if (is_bool($result)) { return json_encode($result); } $user = $request->user(); return json_encode(array( 'payload' => array( 'userId' => $user->getAuthIdentifier(), 'userInfo' => $result, ), )); }
Return the valid authentication response. @param \Nova\Http\Request $request @param mixed $result @return mixed
entailment
public function broadcast(array $channels, $event, array $payload = array()) { $connection = $this->redis->connection($this->connection); $payload = json_encode(array( 'event' => $event, 'data' => $payload )); foreach ($this->formatChannels($channels) as $channel) { $connection->publish($channel, $payload); } }
{@inheritdoc}
entailment
public function authenticate(Request $request) { $channelName = $request->input('channel_name'); $channel = preg_replace('/^(private|presence)\-/', '', $channelName, 1, $count); if (($count == 1) && is_null($user = $request->user())) { // For the private and presence channels, the Broadcasting needs a valid User instance, // but it is not available for the non authenticated users (guests) within Auth System. // For the guests, we will use a cached GuestUser instance, with a random string as ID. $request->setUserResolver(function () { if (! isset($this->authGuest)) { $session = $this->container['session']; if (empty($id = $session->get('broadcasting.guest'))) { $session->set('broadcasting.guest', $id = dechex(time()) . Str::random(16)); } return $this->authGuest = new GuestUser($id); } return $this->authGuest; }); } return $this->verifyUserCanAccessChannel($request, $channel); }
Authenticate the incoming request for a given channel. @param \Nova\Http\Request $request @return mixed
entailment