sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function registerServiceProvider($properties)
{
$namespace = $this->resolveNamespace($properties);
$name = Str::studly(
isset($properties['type']) ? $properties['type'] : 'package'
);
// The main service provider from a package should be named like:
// AcmeCorp\Pages\Providers\PackageServiceProvider
$provider = "{$namespace}\\Providers\\{$name}ServiceProvider";
if (! class_exists($provider)) {
// We will try to find the alternate service provider, named like:
// AcmeCorp\Pages\PageServiceProvider
$name = Str::singular(
$properties['basename']
);
if (! class_exists($provider = "{$namespace}\\{$name}ServiceProvider")) {
return;
}
}
$this->app->register($provider);
} | Register the Package Service Provider.
@param array $properties
@return void
@throws \Nova\Packages\FileMissingException | entailment |
public function dispatch($command)
{
if (! is_null($this->queueResolver) && $this->commandShouldBeQueued($command)) {
return $this->dispatchToQueue($command);
} else {
return $this->dispatchNow($command);
}
} | Dispatch a command to its appropriate handler.
@param mixed $command
@return mixed | entailment |
public function dispatchNow($command, $handler = null)
{
if (! is_null($handler) || ! is_null($handler = $this->getCommandHandler($command))) {
$callback = function ($command) use ($handler)
{
return $handler->handle($command);
};
}
// The command is self handling.
else {
$callback = function ($command)
{
return $this->container->call(array($command, 'handle'));
};
}
$pipeline = new Pipeline($this->container, $this->pipes);
return $pipeline->handle($command, $callback);
} | Dispatch a command to its appropriate handler in the current process.
@param mixed $command
@param mixed $handler
@return mixed | entailment |
public function getCommandHandler($command)
{
$key = get_class($command);
if (array_key_exists($key, $this->handlers)) {
$handler = $this->handlers[$key];
return $this->container->make($handler);
}
} | Retrieve the handler for a command.
@param mixed $command
@return bool|mixed | entailment |
protected function detectWebEnvironment($environments)
{
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if ($environments instanceof Closure) {
return call_user_func($environments);
}
foreach ($environments as $environment => $hosts) {
// To determine the current environment, we'll simply iterate through the possible
// environments and look for the host that matches the host for this request we
// are currently processing here, then return back these environment's names.
foreach ((array) $hosts as $host) {
if ($this->isMachine($host)) return $environment;
}
}
return 'production';
} | Set the application environment for a web request.
@param array|string $environments
@return string | entailment |
public function handle()
{
$type = $this->option('type');
if (! in_array($type, array('module', 'theme', 'package'))) {
return $this->error('Invalid package type specified.');
}
$name = $this->argument('name');
if (strpos($name, '/') > 0) {
list ($vendor, $name) = explode('/', $name);
} else {
$vendor = 'AcmeCorp';
}
if ($type == 'module') {
$namespace = $this->packages->getModulesNamespace();
$vendor = basename(str_replace('\\', '/', $namespace));
} else if ($type == 'theme') {
$namespace = $this->packages->getThemesNamespace();
$vendor = basename(str_replace('\\', '/', $namespace));
}
if (Str::length($name) > 3) {
$slug = Str::snake($name);
} else {
$slug = Str::lower($name);
}
$this->data['slug'] = $slug;
//
if (Str::length($slug) > 3) {
$name = Str::studly($slug);
} else {
$name = Str::upper($slug);
}
$this->data['name'] = $name;
//
$this->data['package'] = $package = Str::studly($vendor) .'/' .$name;
$this->data['lower_package'] = Str::snake($vendor, '-') .'/' .str_replace('_', '-', $slug);
$this->data['namespace'] = str_replace('/', '\\', $package);
//
$config = $this->container['config'];
$this->data['author'] = $config->get('packages.author.name');
$this->data['email'] = $config->get('packages.author.email');
$this->data['homepage'] = $config->get('packages.author.homepage');
$this->data['license'] = 'MIT';
if ($this->option('quick')) {
return $this->generate($type);
}
$this->stepOne($type);
} | Execute the console command.
@return mixed | entailment |
private function stepOne($type)
{
$input = $this->ask('Please enter the name of the Package:', $this->data['name']);
if (Str::length($input) > 3) {
$name = Str::studly($input);
} else {
$name = Str::upper($input);
}
$this->data['name'] = $name;
//
$input = $this->ask('Please enter the slug of the Package:', $this->data['slug']);
if (Str::length($input) > 3) {
$slug = Str::snake($input);
} else {
$slug = Str::lower($input);
}
$this->data['slug'] = $slug;
if ($type == 'module') {
$namespace = $this->packages->getModulesNamespace();
$vendor = basename(str_replace('\\', '/', $namespace));
} else if ($type == 'theme') {
$namespace = $this->packages->getThemesNamespace();
$vendor = basename(str_replace('\\', '/', $namespace));
} else {
if (strpos($this->data['package'], '/') > 0) {
list ($vendor) = explode('/', $this->data['package']);
} else {
$vendor = 'AcmeCorp';
}
if (empty($vendor = $this->ask('Please enter the vendor of the Package:', $vendor))) {
$vendor = 'AcmeCorp';
}
}
$this->data['package'] = Str::studly($vendor) .'/' .$name;
$this->data['lower_package'] = Str::snake($vendor, '-') .'/' .str_replace('_', '-', $slug);
//
$this->data['namespace'] = $this->ask('Please enter the namespace of the Package:', $this->data['namespace']);
$this->data['license'] = $this->ask('Please enter the license of the Package:', $this->data['license']);
$this->comment('You have provided the following information:');
$this->comment('Name: ' .$this->data['name']);
$this->comment('Slug: ' .$this->data['slug']);
$this->comment('Package: ' .$this->data['package']);
$this->comment('Namespace: ' .$this->data['namespace']);
$this->comment('License: ' .$this->data['license']);
if ($this->confirm('Do you wish to continue?')) {
$this->generate($type);
} else {
return $this->stepOne($type);
}
return true;
} | Step 1: Configure Package.
@param string $type
@return mixed | entailment |
protected function generate($type)
{
$slug = $this->data['slug'];
if ($type == 'module') {
$path = $this->getModulePath($slug);
} else if ($type == 'theme') {
$path = $this->getThemePath($slug);
} else {
$path = $this->getPackagePath($slug);
}
if ($this->files->exists($path)) {
$this->error('The Package [' .$slug .'] already exists!');
return false;
}
$steps = array(
'Generating folders...' => 'generateFolders',
'Generating files...' => 'generateFiles',
'Generating .gitkeep ...' => 'generateGitkeep',
'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), $type);
$progress->advance();
}
$progress->finish();
$this->info("\nGenerating optimized class loader");
$this->container['composer']->dumpOptimized();
$this->info("Package generated successfully.");
} | Generate the Package. | entailment |
protected function generateFolders($type)
{
$slug = $this->data['slug'];
if ($type == 'module') {
$path = $this->packages->getModulesPath();
$packagePath = $this->getModulePath($slug);
$mode = 'module';
} else if ($type == 'theme') {
$path = $this->packages->getThemesPath();
$packagePath = $this->getThemePath($slug);
$mode = 'theme';
} else {
$path = $this->packages->getPackagesPath();
$packagePath = $this->getPackagePath($slug);
$mode = $this->option('extended') ? 'extended' : 'default';
}
if (! $this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0755, true, true);
}
$this->files->makeDirectory($packagePath);
// Generate the Package directories.
$packageFolders = $this->packageFolders[$mode];
foreach ($packageFolders as $folder) {
$path = $packagePath .$folder;
$this->files->makeDirectory($path);
}
// Generate the Language inner directories.
$languageFolders = $this->getLanguagePaths($slug, $type);
foreach ($languageFolders as $folder) {
$path = $packagePath .$folder;
$this->files->makeDirectory($path);
}
} | Generate defined Package folders.
@param string $type
@return void | entailment |
protected function generateFiles($type)
{
if ($type == 'module') {
$mode = 'module';
$this->data['type'] = 'Module';
$this->data['lower_type'] = 'module';
} else if ($type == 'theme') {
$mode = 'theme';
$this->data['type'] = 'Theme';
$this->data['lower_type'] = 'theme';
} else {
$mode = $this->option('extended') ? 'extended' : 'default';
$this->data['type'] = 'Package';
$this->data['lower_type'] = 'package';
}
$packageFiles = $this->packageFiles[$mode];
//
$slug = $this->data['slug'];
if ($type == 'module') {
$packagePath = $this->getModulePath($slug);
} else if ($type == 'theme') {
$packagePath = $this->getThemePath($slug);
} else {
$packagePath = $this->getPackagePath($slug);
}
foreach ($packageFiles as $key => $file) {
$file = $this->formatContent($file);
$this->files->put(
$this->getDestinationFile($file, $packagePath), $this->getStubContent($key, $mode)
);
}
// Generate the Language files
$content ='<?php
return array (
);';
$languageFolders = $this->getLanguagePaths($slug, $type);
foreach ($languageFolders as $folder) {
$path = $packagePath .$folder .DS .'messages.php';
$this->files->put($path, $content);
}
} | Generate defined Package files.
@param string $type
@return void | entailment |
protected function generateGitkeep($type)
{
$slug = $this->data['slug'];
if ($type == 'module') {
$packagePath = $this->getModulePath($slug);
$mode = 'module';
} else if ($type == 'theme') {
$packagePath = $this->getThemePath($slug);
$mode = 'theme';
} else {
$packagePath = $this->getPackagePath($slug);
$mode = $this->option('extended') ? 'extended' : 'default';
}
$packageFolders = $this->packageFolders[$mode];
foreach ($packageFolders as $folder) {
$path = $packagePath .$folder;
//
$files = $this->files->glob($path .'/*');
if(! empty($files)) continue;
$gitkeep = $path .DS .'.gitkeep';
$this->files->put($gitkeep, '');
}
} | Generate .gitkeep files within generated folders.
@param string $type
@return void | entailment |
protected function updateComposerJson($type)
{
// If the generated package is a Module.
if ($type == 'module') {
$namespace = 'Modules\\';
$directory = 'modules/';
}
// If the generated package is a Theme.
else if ($type == 'theme') {
$namespace = 'Themes\\';
$directory = 'themes/';
}
// Standard processing for the Packages.
else {
$namespace = $this->data['namespace'] .'\\';
$directory = 'packages/' . $this->data['name'] . "/src/";
}
$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 (! Arr::has($config, "autoload.psr-4.$namespace")) {
Arr::set($config, "autoload.psr-4.$namespace", $directory);
$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 |
protected function getPackagePath($slug = null)
{
if (! is_null($slug)) {
return $this->packages->getPackagePath($slug);
}
return $this->packages->getPackagesPath();
} | Get the path to the Package.
@param string $slug
@return string | entailment |
protected function getModulePath($slug = null)
{
if (! is_null($slug)) {
return $this->packages->getModulePath($slug);
}
return $this->packages->getModulesPath();
} | Get the path to the Package.
@param string $slug
@return string | entailment |
protected function getThemePath($slug = null)
{
if (! is_null($slug)) {
return $this->packages->getThemePath($slug);
}
return $this->packages->getThemesPath();
} | Get the path to the Package.
@param string $slug
@return string | entailment |
protected function getDestinationFile($file, $packagePath)
{
$slug = $this->data['slug'];
return $packagePath .$this->formatContent($file);
} | Get destination file.
@param string $file
@param string $packagePath
@return string | entailment |
protected function getStubContent($key, $mode)
{
$packageStubs = $this->packageStubs[$mode];
//
$stub = $packageStubs[$key];
$path = __DIR__ .DS .'stubs' .DS .$stub .'.stub';
$content = $this->files->get($path);
return $this->formatContent($content);
} | Get stub content by key.
@param int $key
@param bool $mode
@return string | entailment |
public function dispatch(...$params): ResponseInterface
{
/**
* @var RequestInterface $request
* @var ResponseInterface $response
*/
list($request, $response) = $params;
try {
// before dispatcher
$this->beforeDispatch($request, $response);
// request middlewares
$middlewares = $this->requestMiddleware();
$request = RequestContext::getRequest();
$requestHandler = new RequestHandler($middlewares, $this->handlerAdapter);
$response = $requestHandler->handle($request);
} catch (\Throwable $throwable) {
/* @var ErrorHandler $errorHandler */
$errorHandler = App::getBean(ErrorHandler::class);
$response = $errorHandler->handle($throwable);
}
$this->afterDispatch($response);
return $response;
} | Do dispatcher
@param array ...$params
@return \Psr\Http\Message\ResponseInterface
@throws \InvalidArgumentException | entailment |
protected function beforeDispatch(RequestInterface $request, ResponseInterface $response)
{
RequestContext::setRequest($request);
RequestContext::setResponse($response);
// Trigger 'Before Request' event
App::trigger(HttpServerEvent::BEFORE_REQUEST);
} | before dispatcher
@param RequestInterface $request
@param ResponseInterface $response
@throws \InvalidArgumentException | entailment |
protected function afterDispatch($response)
{
if (!$response instanceof Response) {
$response = RequestContext::getResponse()->auto($response);
}
// Handle Response
$response->send();
// Release system resources
App::trigger(AppEvent::RESOURCE_RELEASE);
// Trigger 'After Request' event
App::trigger(HttpServerEvent::AFTER_REQUEST);
} | If $response is not an instance of Response,
usually return by Action of Controller,
then the auto() method will format the result
and return a suitable response
@param mixed $response
@throws \InvalidArgumentException | entailment |
public function getHeader($name)
{
$key = strtolower($name);
if (isset($this->responseHeader[$key])) {
if (!isset($this->responseHeader[$key]['name']) &&
is_array($this->responseHeader[$key])) {
$values = array();
foreach ($this->responseHeader[$key] as $header) {
$values[] = $header['value'];
}
return $values;
} else {
return $this->responseHeader[$key]['value'];
}
}
return;
} | Recupera o valor um campo de cabeçalho da resposta HTTP.
@param string $name Nome do campo de cabeçalho.
@return string O valor do campo ou NULL se não estiver existir. | entailment |
public function getHeaderDate($name)
{
$date = $this->getHeader($name);
if (!is_null($date) && !empty($date)) {
return strtotime($date);
}
} | Recupera um valor como unix timestamp de um campo de cabeçalho da resposta HTTP.
@param string $name Nome do campo de cabeçalho.
@return int UNIX Timestamp ou NULL se não estiver definido. | entailment |
public function setRawResponse($response)
{
$parts = explode("\r\n\r\n", $response);
if (count($parts) == 2) {
$matches = array();
$this->responseBody = $parts[1];
if (preg_match_all(
'/(HTTP\/[1-9]\.[0-9]\s+(?<statusCode>\d+)\s+(?<statusMessage>.*)'.
"|(?<headerName>[^:]+)\\s*:\\s*(?<headerValue>.*))\r\n/m",
$parts[0], $matches)) {
foreach ($matches['statusCode'] as $offset => $match) {
if (!empty($match)) {
$this->statusCode = (int) $match;
$this->statusMessage = $matches['statusMessage'][$offset];
break;
}
}
foreach ($matches['headerName'] as $offset => $name) {
if (!empty($name)) {
$key = strtolower($name);
$header = array('name' => $name,
'value' => $matches['headerValue'][$offset],
);
if (isset($this->responseHeader[$key])) {
if (isset($this->responseHeader[$key]['name'])) {
$this->responseHeader[$key] = array(
$this->responseHeader[$key],
);
}
$this->responseHeader[$key][] = $header;
} else {
$this->responseHeader[$key] = $header;
}
}
}
}
} else {
$this->responseBody = $response;
}
} | Define a resposta da requisição HTTP.
@param string $response Toda a resposta da requisição
@param \Moip\Http\CookieManager | entailment |
public function pop($queue = null)
{
$original = $queue ?: $this->default;
$queue = $this->getQueue($queue);
if ( ! is_null($this->expire)) {
$this->migrateAllExpiredJobs($queue);
}
$job = $this->getConnection()->lpop($queue);
if ( ! is_null($job)) {
$this->getConnection()->zadd($queue.':reserved', $this->getTime() + $this->expire, $job);
return new RedisJob($this->container, $this, $job, $original);
}
} | Pop the next job off of the queue.
@param string $queue
@return \Nova\Queue\Jobs\Job|null | entailment |
public function deleteReserved($queue, $job)
{
$this->getConnection()->zrem($this->getQueue($queue).':reserved', $job);
} | Delete a reserved job from the queue.
@param string $queue
@param string $job
@return void | entailment |
public function migrateExpiredJobs($from, $to)
{
$options = ['cas' => true, 'watch' => $from, 'retry' => 10];
$this->getConnection()->transaction($options, function ($transaction) use ($from, $to)
{
// First we need to get all of jobs that have expired based on the current time
// so that we can push them onto the main queue. After we get them we simply
// remove them from this "delay" queues. All of this within a transaction.
$jobs = $this->getExpiredJobs(
$transaction, $from, $time = $this->getTime()
);
// If we actually found any jobs, we will remove them from the old queue and we
// will insert them onto the new (ready) "queue". This means they will stand
// ready to be processed by the queue worker whenever their turn comes up.
if (count($jobs) > 0) {
$this->removeExpiredJobs($transaction, $from, $time);
$this->pushExpiredJobsOntoNewQueue($transaction, $to, $jobs);
}
});
} | Migrate the delayed jobs that are ready to the regular queue.
@param string $from
@param string $to
@return void | entailment |
protected function removeExpiredJobs($transaction, $from, $time)
{
$transaction->multi();
$transaction->zremrangebyscore($from, '-inf', $time);
} | Remove the expired jobs from a given queue.
@param \Predis\Transaction\MultiExec $transaction
@param string $from
@param int $time
@return void | entailment |
public function get($name)
{
try {
return \strpos($name, '.') === false
? parent::get($name)
: $this->getRecursive($name);
} catch (NotFoundException $exception) {
throw new ContainerValueNotFoundException(
\sprintf('No entry or class found for "%s"', $name),
$exception->getCode(),
$exception
);
} catch (\Throwable $exception) {
throw new ContainerException($exception->getMessage(), $exception->getCode(), $exception);
}
} | Returns an entry of the container by its name.
@see \DI\Container::get
@param string $name
@throws ContainerValueNotFoundException
@throws ContainerException
@return mixed | entailment |
public function has($name)
{
if (\strpos($name, '.') === false) {
return parent::has($name);
}
try {
$this->getRecursive($name);
} catch (\Throwable $exception) {
return false;
}
return true;
} | Test if the container can provide something for the given name.
@see \DI\Container::has
@param string $name
@throws \InvalidArgumentException
@return mixed | entailment |
private function getRecursive(string $key, array $parent = null)
{
if ($parent !== null ? \array_key_exists($key, $parent) : parent::has($key)) {
return $parent !== null ? $parent[$key] : parent::get($key);
}
$keySegments = \explode('.', $key);
$keyParts = [];
while (\count($keySegments) > 1) {
\array_unshift($keyParts, \array_pop($keySegments));
$subKey = \implode('.', $keySegments);
if ($parent !== null ? \array_key_exists($subKey, $parent) : parent::has($subKey)) {
$parent = $parent !== null ? $parent[$subKey] : parent::get($subKey);
if (!\is_array($parent)) {
break;
}
return $this->getRecursive(\implode('.', $keyParts), $parent);
}
}
throw new NotFoundException(\sprintf('Entry "%s" not found', $key));
} | @param string $key
@param array|null $parent
@throws NotFoundException
@return mixed | entailment |
public function showAction(Request $request, $slug)
{
$query = trim(strtolower(strip_tags($request->get('query', ''))));
$search = null;
// if we have a slug - there was a search before
if ($slug) {
/** @var \Genj\FaqBundle\Entity\Search $search */
$search = $this->getSearchRepository()->findOneBySlug($slug);
}
// just without slug the query is interesting
elseif ($query != '') {
// is my query a plain number?
// than redirect there right away
/** @var \Genj\FaqBundle\Entity\Question $question */
$question = $this->getQuestionRepository()->findOneById($query);
if ($question) {
return $this->redirectToRoute($question->getRouteName(), $question->getRouteParameters());
}
/** @var \Genj\FaqBundle\Entity\Search $search */
$search = $this->getSearchRepository()->findOneByHeadline($query);
}
// and if we don't have anything yet - we start from scratch
if (!$search and $query != '') {
/** @var \Genj\FaqBundle\Entity\Search $search */
$className = $this->getSearchRepository()->getClassName();
$search = new $className();
$search->setHeadline($query);
}
// increase search count
if ($search) {
$search->setSearchCount($search->getSearchCount() + 1);
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
$em->persist($search);
$em->flush();
}
return $this->render(
'GenjFaqBundle:Search:show.html.twig',
array(
'query' => $query,
'search' => $search
)
);
} | shows search results for previous queries
@param Request $request
@param string $slug
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function listMostPopularAction($max = 3)
{
$queries = $this->getSearchRepository()->retrieveMostPopular($max);
return $this->render(
'GenjFaqBundle:Search:list_most_popular.html.twig',
array(
'queries' => $queries,
'max' => $max
)
);
} | list most popular search queries based on searchCount
@param int $max
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function handle()
{
$type = $this->option('type');
if (! is_null($type) && ! in_array($type, array('package', 'module', 'theme'))) {
return $this->error("Invalid Packages type [$type].");
}
$packages = $this->getPackages($type);
if (empty($packages)) {
if (! is_null($type)) {
return $this->error("Your application doesn't have any Packages of type [$type].");
}
return $this->error("Your application doesn't have any Packages.");
}
$this->displayPackages($packages);
} | Execute the console command.
@return mixed | entailment |
protected function getPackages($type)
{
$packages = $this->packages->all();
if (! is_null($type)) {
$packages = $packages->where('type', $type);
}
$results = array();
foreach ($packages->sortBy('basename') as $package) {
$results[] = $this->getPackageInformation($package);
}
return array_filter($results);
} | Get all Packages.
@return array | entailment |
protected function getPackageInformation($package)
{
$location = ($package['location'] === 'local') ? 'Local' : 'Vendor';
$type = Str::title($package['type']);
if ($this->packages->isEnabled($package['slug'])) {
$status = 'Enabled';
} else {
$status = 'Disabled';
}
return array(
'name' => $package['name'],
'slug' => $package['slug'],
'order' => $package['order'],
'location' => $location,
'type' => $type,
'status' => $status,
);
} | Returns Package manifest information.
@param string $package
@return array | entailment |
protected function resolveByPath($filePath)
{
$this->data['filename'] = $this->makeFileName($filePath);
$this->data['namespace'] = $this->getNamespace($filePath);
$this->data['path'] = $this->getBaseNamespace();
$this->data['className'] = basename($filePath);
//
$this->data['fullEvent'] = $option = $this->option('event');
$this->data['event'] = class_basename($option);
} | Resolve Container after getting file path.
@param string $filePath
@return array | entailment |
public function driver($driver = null)
{
$driver = $driver ?: $this->getDefaultDriver();
if (! isset($this->drivers[$driver])) {
$this->drivers[$driver] = $this->createDriver($driver);
}
return $this->drivers[$driver];
} | Get a driver instance.
@param string $driver
@return mixed | entailment |
protected function compileEchos($value)
{
$difference = strlen($this->contentTags[0]) - strlen($this->escapedTags[0]);
if ($difference > 0) {
return $this->compileEscapedEchos($this->compileRegularEchos($value));
}
return $this->compileRegularEchos($this->compileEscapedEchos($value));
} | Compile Template echos into valid PHP.
@param string $value
@return string | entailment |
protected function compileStatements($value)
{
$callback = function($match)
{
if (method_exists($this, $method = 'compile' .ucfirst($match[1]))) {
$match[0] = call_user_func(array($this, $method), Arr::get($match, 3));
}
return isset($match[3]) ? $match[0] : $match[0] .$match[2];
};
return preg_replace_callback('/\B@(\w+)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?/x', $callback, $value);
} | Compile Template Statements that start with "@"
@param string $value
@return mixed | entailment |
protected function compileRegularEchos($value)
{
$pattern = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->contentTags[0], $this->contentTags[1]);
$callback = function($matches)
{
$whitespace = empty($matches[3]) ? '' : $matches[3] .$matches[3];
return $matches[1] ? substr($matches[0], 1) : '<?php echo ' .$this->compileEchoDefaults($matches[2]) .'; ?>' .$whitespace;
};
return preg_replace_callback($pattern, $callback, $value);
} | Compile the "regular" echo statements.
@param string $value
@return string | entailment |
protected function compileExtends($expression)
{
$expression = $this->stripParentheses($expression);
$data = "<?php echo \$__env->make($expression, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
$this->footer[] = $data;
return '';
} | Compile the extends statements into valid PHP.
@param string $expression
@return string | entailment |
public function stripParentheses($expression)
{
if (Str::startsWith($expression, '(') && Str::endsWith($expression, ')')) {
$expression = substr($expression, 1, -1);
}
return $expression;
} | Strip the parentheses from the given expression.
@param string $expression
@return string | entailment |
public function getOptions(array $config)
{
$options = array_get($config, 'options', array());
return array_diff_key($this->options, $options) + $options;
} | Get the PDO options based on the configuration.
@param array $config
@return array | entailment |
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
} | Create a new PDO connection.
@param string $dsn
@param array $config
@param array $options
@return PDO | entailment |
public function push($filename, LoggerInterface $logger)
{
$destination = $this->createPath($filename);
$logger->info(sprintf('Uploading %s to: %s', $filename, $destination));
$process = ProcessBuilder::create($this->options)
->setPrefix(array('s3cmd', 'put'))
->add($filename)
->add($destination)
->setTimeout($this->timeout)
->getProcess();
$process->run();
if (!$process->isSuccessful() || false !== strpos($process->getErrorOutput(), 'ERROR:')) {
throw new \RuntimeException($process->getErrorOutput());
}
return $this->get($filename);
} | {@inheritdoc} | entailment |
public function get($key)
{
$destination = $this->createPath($key);
$process = ProcessBuilder::create($this->options)
->setPrefix(array('s3cmd', 'info'))
->add($destination)
->setTimeout($this->timeout)
->getProcess();
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
$output = $process->getOutput();
preg_match('#File size\:\s+(\d+)\s+Last mod\:\s+(.+)#', $output, $matches);
if (3 !== count($matches)) {
throw new \RuntimeException(sprintf('Error processing result: %s', $output));
}
return new Backup($destination, $matches[1], new \DateTime($matches[2]));
} | {@inheritdoc} | entailment |
public function all()
{
$process = ProcessBuilder::create($this->options)
->setPrefix(array('s3cmd', 'ls'))
->add(trim($this->bucket, '/').'/')
->setTimeout($this->timeout)
->getProcess();
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
return new BackupCollection($this->parseS3CmdListOutput($process->getOutput()));
} | {@inheritdoc} | entailment |
private function parseS3CmdListOutput($output)
{
$backups = array();
if (null === $output) {
return $backups;
}
foreach (explode("\n", $output) as $row) {
if ('' === $row) {
continue;
}
$backups[] = $this->parseS3CmdListRow($row);
}
return $backups;
} | @param string $output
@return Backup[] | entailment |
private function parseS3CmdListRow($row)
{
$columns = explode(' ', preg_replace('/\s+/', ' ', $row));
if (4 !== count($columns)) {
throw new \RuntimeException(sprintf('Error processing result: %s', $row));
}
return new Backup($columns[3], $columns[2], new \DateTime(sprintf('%s %s', $columns[0], $columns[1])));
} | @param string
@return Backup | entailment |
public function findMany($ids, $columns = array('*'))
{
if (empty($ids)) {
return $this->model->newCollection();
}
$keyName = $this->model->getQualifiedKeyName();
$this->query->whereIn($keyName, $ids);
return $this->get($columns);
} | Find a model by its primary key.
@param array $ids
@param array $columns
@return \Nova\Database\ORM\Model|Collection|static | entailment |
public function get($columns = array('*'))
{
$models = $this->getModels($columns);
if (count($models) > 0) {
$models = $this->eagerLoadRelations($models);
}
return $this->model->newCollection($models);
} | Execute the query as a "select" statement.
@param array $columns
@return \Nova\Database\ORM\Collection|static[] | entailment |
public function paginate($perPage = null, $columns = array('*'), $pageName = 'page', $page = null)
{
if (is_null($page)) {
$page = Paginator::resolveCurrentPage($pageName);
}
$path = Paginator::resolveCurrentPath($pageName);
if (is_null($perPage)) {
$perPage = $this->model->getPerPage();
}
$total = $this->query->getPaginationCount();
if ($total > 0) {
$results = $this->forPage($page, $perPage)->get($columns);
} else {
$results = $this->model->newCollection();
}
return new Paginator($results, $total, $perPage, $page, compact('path', 'pageName'));
} | Paginate the given query.
@param int $perPage
@param array $columns
@param string $pageName
@param int|null $page
@return \Nova\Pagination\Paginator
@throws \InvalidArgumentException | entailment |
public function simplePaginate($perPage = null, $columns = array('*'), $pageName = 'page', $page = null)
{
if (is_null($page)) {
$page = Paginator::resolveCurrentPage($pageName);
}
$path = Paginator::resolveCurrentPath($pageName);
if (is_null($perPage)) {
$perPage = $this->model->getPerPage();
}
$offset = ($page - 1) * $perPage;
$results = $this->skip($offset)->take($perPage + 1)->get($columns);
return new SimplePaginator($results, $perPage, $page, compact('path', 'pageName'));
} | Paginate the given query into a simple paginator.
@param int $perPage
@param array $columns
@param string $pageName
@param int|null $page
@return \Nova\Pagination\SimplePaginator | entailment |
public function increment($column, $amount = 1, array $extra = array())
{
$extra = $this->addUpdatedAtColumn($extra);
return $this->query->increment($column, $amount, $extra);
} | Increment a column's value by a given amount.
@param string $column
@param int $amount
@param array $extra
@return int | entailment |
public function decrement($column, $amount = 1, array $extra = array())
{
$extra = $this->addUpdatedAtColumn($extra);
return $this->query->decrement($column, $amount, $extra);
} | Decrement a column's value by a given amount.
@param string $column
@param int $amount
@param array $extra
@return int | entailment |
protected function addUpdatedAtColumn(array $values)
{
if (! $this->model->usesTimestamps()) return $values;
$column = $this->model->getUpdatedAtColumn();
return array_add($values, $column, $this->model->freshTimestampString());
} | Add the "updated at" column to an array of values.
@param array $values
@return array | entailment |
public function delete()
{
if (isset($this->onDelete)) {
return call_user_func($this->onDelete, $this);
}
return $this->query->delete();
} | Delete a record from the database.
@return mixed | entailment |
protected function loadRelation(array $models, $name, Closure $constraints)
{
$relation = $this->getRelation($name);
$relation->addEagerConstraints($models);
call_user_func($constraints, $relation);
$models = $relation->initRelation($models, $name);
$results = $relation->getEager();
return $relation->match($models, $results, $name);
} | Eagerly load the relationship on a set of models.
@param array $models
@param string $name
@param \Closure $constraints
@return array | entailment |
public function getRelation($relation)
{
$query = Relation::noConstraints(function() use ($relation)
{
return $this->getModel()->$relation();
});
$nested = $this->nestedRelations($relation);
if (count($nested) > 0) {
$query->getQuery()->with($nested);
}
return $query;
} | Get the relation instance for the given relation name.
@param string $relation
@return \Nova\Database\ORM\Relations\Relation | entailment |
protected function isNested($name, $relation)
{
$dots = str_contains($name, '.');
return $dots && Str::startsWith($name, $relation.'.');
} | Determine if the relationship is nested.
@param string $name
@param string $relation
@return bool | entailment |
public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
{
if (strpos($relation, '.') !== false) {
return $this->hasNested($relation, $operator, $count, $boolean, $callback);
}
$relation = $this->getHasRelationQuery($relation);
$query = $relation->getRelationCountQuery($relation->getRelated()->newQuery(), $this);
if ($callback) call_user_func($callback, $query);
return $this->addHasWhere($query, $relation, $operator, $count, $boolean);
} | Add a relationship count condition to the query.
@param string $relation
@param string $operator
@param int $count
@param string $boolean
@param \Closure|null $callback
@return \Nova\Database\ORM\Builder|static | entailment |
protected function mergeWheresToHas(Builder $hasQuery, Relation $relation)
{
$relationQuery = $relation->getBaseQuery();
$hasQuery = $hasQuery->getModel()->removeGlobalScopes($hasQuery);
$hasQuery->mergeWheres(
$relationQuery->wheres, $relationQuery->getBindings()
);
$this->query->mergeBindings($hasQuery->getQuery());
} | Merge the "wheres" from a relation query to a has query.
@param \Nova\Database\ORM\Builder $hasQuery
@param \Nova\Database\ORM\Relations\Relation $relation
@return void | entailment |
public function withCount($relations)
{
if (is_string($relations)) $relations = func_get_args();
// If no columns are set, add the default * columns.
if (is_null($this->query->columns)) {
$this->query->select($this->query->from .'.*');
}
$relations = $this->parseRelations($relations);
foreach ($relations as $name => $constraints) {
$segments = explode(' ', $name);
if ((count($segments) == 3) && (Str::lower($segments[1]) == 'as')) {
list($name, $alias) = array($segments[0], $segments[2]);
} else {
unset($alias);
}
$relation = $this->getHasRelationQuery($name);
// Here we will get the relationship count query and prepare to add it to the main query
// as a sub-select. First, we'll get the "has" query and use that to get the relation
// count query. We will normalize the relation name then append _count as the name.
$query = $relation->getRelationCountQuery($relation->getRelated()->newQuery(), $this);
call_user_func($constraints, $query);
$this->mergeWheresToHas($query, $relation);
$asColumn = snake_case(isset($alias) ? $alias : $name) .'_count';
$this->selectSub($query->getQuery(), $asColumn);
}
return $this;
} | Add subselect queries to count the relations.
@param mixed $relations
@return $this | entailment |
protected function callScope($scope, $parameters)
{
array_unshift($parameters, $this);
return call_user_func_array(array($this->model, $scope), $parameters) ?: $this;
} | Call the given model scope on the underlying model.
@param string $scope
@param array $parameters
@return \Nova\Database\Query\Builder | entailment |
protected function transform($messages, $format, $key)
{
return array_map(function ($message) use ($format, $key)
{
return str_replace(array(':message', ':key'), array($message, $key), $format);
}, (array) $messages);
} | Format an array of messages.
@param array $messages
@param string $format
@param string $messageKey
@return array | entailment |
public function handle()
{
try{
$dbname = $this->argument('dbname');
$connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection') : config('database.default');
$hasDb = \DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$dbname."'");
if(empty($hasDb)) {
\DB::connection($connection)->select('CREATE DATABASE '. $dbname);
$this->info("Database '$dbname' created for '$connection' connection");
}else {
$this->info("Database $dbname already exists for $connection connection");
}
}catch (\Exception $e) {
$this->error($e->getMessage());
}
} | Execute the console command.
@return mixed | entailment |
public function increment($key, $value = 1)
{
$raw = $this->getPayload($key);
$int = ((int) $raw['data']) + $value;
$this->put($key, $int, (int) $raw['time']);
return $int;
} | Increment the value of an item in the cache.
@param string $key
@param mixed $value
@return int | entailment |
public function retrieveActiveBySlug($slug)
{
$query = $this->createQueryBuilder('c')
->where('c.isActive = :isActive')
->andWhere('c.slug = :slug')
->orderBy('c.rank', 'ASC')
->setMaxResults(1)
->getQuery();
$query->setParameter('isActive', true);
$query->setParameter('slug', $slug);
return $query->getOneOrNullResult();
} | @param string $slug
@return mixed | entailment |
public function handle()
{
$fullPath = $this->createBaseMigration();
$this->files->put($fullPath, $this->files->get(__DIR__ .DS .'stubs' .DS .'database.stub'));
$this->info('Migration created successfully!');
$this->call('optimize');
} | Execute the console command.
@return void | entailment |
protected function createBaseMigration()
{
$name = 'create_session_table';
$path = $this->container['path'] .DS .'Database' .DS .'Migrations';
return $this->container['migration.creator']->create($name, $path);
} | Create a base migration file for the session.
@return string | entailment |
protected function createLogger()
{
$log = new Writer(
new Monolog('nova'), $this->app['events']
);
$this->configureHandler($log);
return $log;
} | Create the logger.
@return \Nova\Log\Writer | entailment |
protected function configureHandler(Writer $log)
{
$driver = $this->app['config']['app.log'];
$method = 'configure' .ucfirst($driver) .'Handler';
call_user_func(array($this, $method), $log);
} | Configure the Monolog handlers for the application.
@param \Nova\Foundation\Application $app
@param \Nova\Log\Writer $log
@return void | entailment |
protected function configureDailyHandler(Writer $log)
{
$log->useDailyFiles(
$this->app['path.storage'] .DS .'logs' .DS .'framework.log',
$this->app['config']->get('app.log_max_files', 5)
);
} | Configure the Monolog handlers for the application.
@param \Nova\Log\Writer $log
@return void | entailment |
public function delete($id)
{
$db = new DatabaseManager();
$connection = $db->getDbh();
$sql = 'DELETE from :table WHERE id=:id';
$sql = str_replace(':table', $this->tableName, $sql);
$statement = $connection->prepare($sql);
// $statement->bindParam(':table', $this->tableName);
$statement->bindParam(':id', $id, \PDO::PARAM_INT);
$queryWasSuccessful = $statement->execute();
return $queryWasSuccessful;
} | delete record for given ID - return true/false depending on delete success
@param $id
@return bool | entailment |
public function create($object)
{
$db = new DatabaseManager();
$connection = $db->getDbh();
$objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object);
$fields = array_keys($objectAsArrayForSqlInsert);
$insertFieldList = DatatbaseUtility::fieldListToInsertString($fields);
$valuesFieldList = DatatbaseUtility::fieldListToValuesString($fields);
$sql = 'INSERT into :table :insertFieldList :valuesFieldList';
$sql = str_replace(':table', $this->tableName, $sql);
$sql = str_replace(':insertFieldList', $insertFieldList, $sql);
$sql = str_replace(':valuesFieldList', $valuesFieldList, $sql);
$statement = $connection->prepare($sql);
$statement->execute($objectAsArrayForSqlInsert);
$queryWasSuccessful = ($statement->rowCount() > 0);
if($queryWasSuccessful) {
return $connection->lastInsertId();
} else {
return -1;
}
} | insert new record into the DB table
returns new record ID if insertion was successful, otherwise -1
@param Object $object
@return integer | entailment |
public function update($object)
{
$id = $object->getId();
$db = new DatabaseManager();
$connection = $db->getDbh();
$objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object);
$fields = array_keys($objectAsArrayForSqlInsert);
$updateFieldList = DatatbaseUtility::fieldListToUpdateString($fields);
$sql = 'UPDATE :table SET :updateFieldList WHERE id=:id';
$sql = str_replace(':table', $this->tableName, $sql);
$sql = str_replace(':updateFieldList', $updateFieldList, $sql);
$statement = $connection->prepare($sql);
// add 'id' to parameters array
$objectAsArrayForSqlInsert['id'] = $id;
$queryWasSuccessful = $statement->execute($objectAsArrayForSqlInsert);
return $queryWasSuccessful;
} | insert new record into the DB table
returns new record ID if insertion was successful, otherwise -1
@param $object
@return bool | entailment |
public function hit($key, $decayMinutes = 1)
{
$this->cache->add($key, 1, $decayMinutes);
return (int) $this->cache->increment($key);
} | Increment the counter for a given key for a given decay time.
@param string $key
@param int $decayMinutes
@return int | entailment |
public function retriesLeft($key, $maxAttempts)
{
$attempts = $this->attempts($key);
return ($attempts === 0) ? $maxAttempts : $maxAttempts - $attempts + 1;
} | Get the number of retries left for the given key.
@param string $key
@param int $maxAttempts
@return int | entailment |
public function clear($key)
{
$this->cache->forget($key);
$this->cache->forget($key .':lockout');
} | Clear the hits and lockout for the given key.
@param string $key
@return void | entailment |
public function evaluate($method, $arguments)
{
$this->authenticator->authenticate($method, $arguments);
return $this->evaluator->evaluate($method, $arguments);
} | Authenticate request and (if successful) map method name to callable
and run it with the given arguments.
@param string $method Method name
@param array $arguments Positional or associative argument array
@return mixed Return value of the callable
@throws Exception\MissingAuth If the no credentials are given
@throws Exception\InvalidAuth If the given credentials are invalid | entailment |
public function resource($name, $controller, array $options = array())
{
$registrar = $this->getRegistrar();
$registrar->register($name, $controller, $options);
} | Route a resource to a controller.
@param string $name
@param string $controller
@param array $options
@return void | entailment |
protected function updateGroupStack(array $attributes)
{
if (! empty($this->groupStack)) {
$old = last($this->groupStack);
$attributes = static::mergeGroup($attributes, $old);
}
$this->groupStack[] = $attributes;
} | Update the group stack with the given attributes.
@param array $attributes
@return void | entailment |
public static function mergeGroup($new, $old)
{
$new['namespace'] = static::formatUsesPrefix($new, $old);
$new['prefix'] = static::formatGroupPrefix($new, $old);
if (isset($new['domain'])) {
unset($old['domain']);
}
$new['where'] = array_merge(
isset($old['where']) ? $old['where'] : array(),
isset($new['where']) ? $new['where'] : array()
);
if (isset($old['as'])) {
$new['as'] = $old['as'] .(isset($new['as']) ? $new['as'] : '');
}
return array_merge_recursive(
Arr::except($old, array('namespace', 'prefix', 'where', 'as')), $new
);
} | Merge the given group attributes.
@param array $new
@param array $old
@return array | entailment |
protected static function formatGroupPrefix($new, $old)
{
$prefix = isset($old['prefix']) ? $old['prefix'] : null;
if (isset($new['prefix'])) {
return trim($prefix, '/') .'/' .trim($new['prefix'], '/');
}
return $prefix;
} | Format the prefix for the new group attributes.
@param array $new
@param array $old
@return string | entailment |
public function getLastGroupPrefix()
{
if (! empty($this->groupStack)) {
$last = end($this->groupStack);
return isset($last['prefix']) ? $last['prefix'] : '';
}
return '';
} | Get the prefix from the last group on the stack.
@return string | entailment |
protected function createRoute($methods, $uri, $action)
{
if (is_callable($action)) {
$action = array('uses' => $action);
}
// If the route is routing to a controller we will parse the route action into
// an acceptable array format before registering it and creating this route
// instance itself. We need to build the Closure that will call this out.
else if ($this->actionReferencesController($action)) {
$action = $this->convertToControllerAction($action);
}
// If no "uses" property has been set, we will dig through the array to find a
// Closure instance within this list. We will set the first Closure we come
// across into the "uses" property that will get fired off by this route.
else if (! isset($action['uses'])) {
$action['uses'] = $this->findActionClosure($action);
}
if (isset($action['middleware']) && is_string($action['middleware'])) {
$action['middleware'] = explode('|', $action['middleware']);
}
$route = $this->newRoute(
$methods, $uri = $this->prefix($uri), $action
);
// If we have groups that need to be merged, we will merge them now after this
// route has already been created and is ready to go. After we're done with
// the merge we will be ready to return the route back out to the caller.
if (! empty($this->groupStack)) {
$this->mergeGroupAttributesIntoRoute($route);
}
$this->addWhereClausesToRoute($route);
return $route;
} | Create a new route instance.
@param array|string $methods
@param string $uri
@param mixed $action
@return \Nova\Routing\Route | entailment |
protected function findActionClosure(array $action)
{
return Arr::first($action, function ($key, $value)
{
return is_callable($value) && is_numeric($key);
});
} | Find the Closure in an action array.
@param array $action
@return \Closure | entailment |
protected function newRoute($methods, $uri, $action)
{
return with(new Route($methods, $uri, $action))
->setRouter($this)
->setContainer($this->container);
} | Create a new Route object.
@param array|string $methods
@param string $uri
@param mixed $action
@return \Nova\Routing\Route | entailment |
protected function addWhereClausesToRoute($route)
{
$route->where(
array_merge($this->patterns, Arr::get($route->getAction(), 'where', array()))
);
return $route;
} | Add the necessary where clauses to the route based on its initial registration.
@param \Nova\Routing\Route $route
@return \Nova\Routing\Route | entailment |
protected function mergeGroupAttributesIntoRoute($route)
{
$action = $this->mergeWithLastGroup($route->getAction());
$route->setAction($action);
} | Merge the group stack with the controller action.
@param \Nova\Routing\Route $route
@return void | entailment |
public function dispatchToRoute(Request $request)
{
// First we will find a route that matches this request. We will also set the
// route resolver on the request so middlewares assigned to the route will
// receive access to this route instance for checking of the parameters.
$route = $this->findRoute($request);
$request->setRouteResolver(function () use ($route)
{
return $route;
});
$this->events->dispatch('router.matched', array($route, $request));
$response = $this->runRouteWithinStack($route, $request);
return $this->prepareResponse($request, $response);
} | Dispatch the request to a route and return the response.
@param \Nova\Http\Request $request
@return mixed | entailment |
protected function runRouteWithinStack(Route $route, Request $request)
{
$skipMiddleware = $this->container->bound('middleware.disable') &&
($this->container->make('middleware.disable') === true);
// Create a Pipeline instance.
$pipeline = new Pipeline(
$this->container, $skipMiddleware ? array() : $this->gatherRouteMiddleware($route)
);
return $pipeline->handle($request, function ($request) use ($route)
{
$response = $route->run($request);
return $this->prepareResponse($request, $response);
});
} | Run the given route within a Stack "onion" instance.
@param \Nova\Routing\Route $route
@param \Nova\Http\Request $request
@return mixed | entailment |
public function gatherRouteMiddleware(Route $route)
{
$middleware = array_map(function ($name)
{
return $this->resolveMiddleware($name);
}, $route->gatherMiddleware());
return Arr::flatten($middleware);
} | Gather the middleware for the given route.
@param \Mini\Routing\Route $route
@return array | entailment |
public function resolveMiddleware($name)
{
if (isset($this->middlewareGroups[$name])) {
return $this->parseMiddlewareGroup($name);
}
return $this->parseMiddleware($name);
} | Resolve the middleware name to class name preserving passed parameters.
@param string $name
@return array | entailment |
protected function parseMiddleware($name)
{
list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
//
$callable = isset($this->middleware[$name]) ? $this->middleware[$name] : $name;
if (is_null($parameters)) {
return $callable;
}
// When the callable is a string, we will add back the parameters before returning.
else if (is_string($callable)) {
return $callable .':' .$parameters;
}
// A callback with parameters; we should create a proper middleware closure for it.
$parameters = explode(',', $parameters);
return function ($passable, $stack) use ($callable, $parameters)
{
return call_user_func_array(
$callable, array_merge(array($passable, $stack), $parameters)
);
};
} | Parse the middleware and format it for usage.
@param string $name
@return array | entailment |
protected function parseMiddlewareGroup($name)
{
$results = array();
foreach ($this->middlewareGroups[$name] as $middleware) {
if (! isset($this->middlewareGroups[$middleware])) {
$results[] = $this->parseMiddleware($middleware);
continue;
}
// The middleware refer a middleware group.
$results = array_merge(
$results, $this->parseMiddlewareGroup($middleware)
);
}
return $results;
} | Parse the middleware group and format it for usage.
@param string $name
@return array | entailment |
protected function performBinding($key, $value, $route)
{
$callback = $this->binders[$key];
return call_user_func($callback, $value, $route);
} | Call the binding callback for the given key.
@param string $key
@param string $value
@param \Nova\Routing\Route $route
@return mixed | entailment |
public function pushMiddlewareToGroup($group, $middleware)
{
if (! array_key_exists($group, $this->middlewareGroups)) {
$this->middlewareGroups[$group] = array();
}
if (! in_array($middleware, $this->middlewareGroups[$group])) {
$this->middlewareGroups[$group][] = $middleware;
}
return $this;
} | Add a middleware to the end of a middleware group.
If the middleware is already in the group, it will not be added again.
@param string $group
@param string $middleware
@return $this | entailment |
public function createClassBinding($binding)
{
return function ($value, $route) use ($binding)
{
// If the binding has an @ sign, we will assume it's being used to delimit
// the class name from the bind method name. This allows for bindings
// to run multiple bind methods in a single class for convenience.
list($className, $method) = array_pad(explode('@', $binding, 2), 2, 'bind');
$instance = $this->container->make($className);
return call_user_func(array($instance, $method), $value, $route);
};
} | Create a class based binding using the IoC container.
@param string $binding
@return \Closure | entailment |
public function prepareResponse($request, $response)
{
if (! $response instanceof SymfonyResponse) {
$response = new Response($response);
}
return $response->prepare($request);
} | Create a response instance from the given value.
@param \Symfony\Component\HttpFoundation\Request $request
@param mixed $response
@return \Nova\Http\Response | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.