language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | laravel | framework | a82a25f58252eab6831a0efde35a17403710abdc.json | add listener optinos | src/Illuminate/Queue/Listener.php | @@ -60,41 +60,59 @@ class Listener
public function __construct($commandPath)
{
$this->commandPath = $commandPath;
- $this->workerCommand = $this->buildWorkerCommand();
+ $this->workerCommand = $this->buildCommandTemplate();
}
/**
* Build the environment specific worker command.
*
* @return string
*/
- protected function buildWorkerCommand()
+ protected function buildCommandTemplate()
{
- $binary = ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false));
+ $command = 'queue:work %s --once --queue=%s --delay=%s --memory=%s --sleep=%s --tries=%s';
- $artisan = defined('ARTISAN_BINARY') ? ProcessUtils::escapeArgument(ARTISAN_BINARY) : 'artisan';
+ return "{$this->phpBinary()} {$this->artisanBinary()} {$command}";
+ }
- $command = 'queue:work %s --once --queue=%s --delay=%s --memory=%s --sleep=%s --tries=%s';
+ /**
+ * Get the PHP binary.
+ *
+ * @return string
+ */
+ protected function phpBinary()
+ {
+ return ProcessUtils::escapeArgument(
+ (new PhpExecutableFinder)->find(false)
+ );
+ }
- return "{$binary} {$artisan} {$command}";
+ /**
+ * Get the Artisan binary.
+ *
+ * @return string
+ */
+ protected function artisanBinary()
+ {
+ return defined('ARTISAN_BINARY')
+ ? ProcessUtils::escapeArgument(ARTISAN_BINARY)
+ : 'artisan';
}
/**
* Listen to the given queue connection.
*
* @param string $connection
* @param string $queue
- * @param string $delay
- * @param string $memory
- * @param int $timeout
+ * @param \Illuminate\Queue\ListenerOptions $options
* @return void
*/
- public function listen($connection, $queue, $delay, $memory, $timeout = 60)
+ public function listen($connection, $queue, ListenerOptions $options)
{
- $process = $this->makeProcess($connection, $queue, $delay, $memory, $timeout);
+ $process = $this->makeProcess($connection, $queue, $options);
while (true) {
- $this->runProcess($process, $memory);
+ $this->runProcess($process, $options->memory);
}
}
@@ -103,43 +121,42 @@ public function listen($connection, $queue, $delay, $memory, $timeout = 60)
*
* @param string $connection
* @param string $queue
- * @param int $delay
- * @param int $memory
- * @param int $timeout
+ * @param \Illuminate\Queue\ListenerOptions $options
* @return \Symfony\Component\Process\Process
*/
- public function makeProcess($connection, $queue, $delay, $memory, $timeout)
+ public function makeProcess($connection, $queue, ListenerOptions $options)
{
$command = $this->workerCommand;
// If the environment is set, we will append it to the command string so the
// workers will run under the specified environment. Otherwise, they will
// just run under the production environment which is not always right.
- if (isset($this->environment)) {
- $command = $this->addEnvironment($command);
+ if (isset($options->environment)) {
+ $command = $this->addEnvironment($command, $options);
}
// Next, we will just format out the worker commands with all of the various
// options available for the command. This will produce the final command
// line that we will pass into a Symfony process object for processing.
$command = $this->formatCommand(
- $command, $connection, $queue, $delay, $memory
+ $command, $connection, $queue, $options
);
return new Process(
- $command, $this->commandPath, null, null, $timeout
+ $command, $this->commandPath, null, null, $options->timeout
);
}
/**
* Add the environment option to the given command.
*
* @param string $command
+ * @param \Illuminate\Queue\ListenerOptions $options
* @return string
*/
- protected function addEnvironment($command)
+ protected function addEnvironment($command, ListenerOptions $options)
{
- return $command.' --env='.ProcessUtils::escapeArgument($this->environment);
+ return $command.' --env='.ProcessUtils::escapeArgument($options->environment);
}
/**
@@ -148,17 +165,17 @@ protected function addEnvironment($command)
* @param string $command
* @param string $connection
* @param string $queue
- * @param int $delay
- * @param int $memory
+ * @param \Illuminate\Queue\ListenerOptions $options
* @return string
*/
- protected function formatCommand($command, $connection, $queue, $delay, $memory)
+ protected function formatCommand($command, $connection, $queue, ListenerOptions $options)
{
return sprintf(
$command,
ProcessUtils::escapeArgument($connection),
ProcessUtils::escapeArgument($queue),
- $delay, $memory, $this->sleep, $this->maxTries
+ $options->delay, $options->memory,
+ $options->sleep, $options->maxTries
);
}
@@ -228,37 +245,4 @@ public function setOutputHandler(Closure $outputHandler)
{
$this->outputHandler = $outputHandler;
}
-
- /**
- * Set the current environment.
- *
- * @param string $environment
- * @return void
- */
- public function setEnvironment($environment)
- {
- $this->environment = $environment;
- }
-
- /**
- * Set the amount of seconds to wait before polling the queue.
- *
- * @param int $sleep
- * @return void
- */
- public function setSleep($sleep)
- {
- $this->sleep = $sleep;
- }
-
- /**
- * Set the amount of times to try a job before logging it failed.
- *
- * @param int $tries
- * @return void
- */
- public function setMaxTries($tries)
- {
- $this->maxTries = $tries;
- }
} | true |
Other | laravel | framework | a82a25f58252eab6831a0efde35a17403710abdc.json | add listener optinos | src/Illuminate/Queue/ListenerOptions.php | @@ -0,0 +1,31 @@
+<?php
+
+namespace Illuminate\Queue;
+
+class ListenerOptions extends WorkerOptions
+{
+ /**
+ * The environment the worker should run in.
+ *
+ * @var string
+ */
+ public $environment;
+
+ /**
+ * Create a new listener options instance.
+ *
+ * @param string $environment
+ * @param int $delay
+ * @param int $memory
+ * @param int $timeout
+ * @param int $sleep
+ * @param int $maxTries
+ * @param bool $force
+ */
+ public function __construct($environment = null, $delay = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 0, $force = false)
+ {
+ $this->environment = $environment;
+
+ parent::__construct($delay, $memory, $timeout, $sleep, $maxTries, $force);
+ }
+} | true |
Other | laravel | framework | a82a25f58252eab6831a0efde35a17403710abdc.json | add listener optinos | tests/Queue/QueueListenerTest.php | @@ -33,7 +33,11 @@ public function testListenerStopsWhenMemoryIsExceeded()
public function testMakeProcessCorrectlyFormatsCommandLine()
{
$listener = new Illuminate\Queue\Listener(__DIR__);
- $process = $listener->makeProcess('connection', 'queue', 1, 2, 3);
+ $options = new Illuminate\Queue\ListenerOptions();
+ $options->delay = 1;
+ $options->memory = 2;
+ $options->timeout = 3;
+ $process = $listener->makeProcess('connection', 'queue', $options);
$escape = '\\' === DIRECTORY_SEPARATOR ? '"' : '\'';
$this->assertInstanceOf('Symfony\Component\Process\Process', $process); | true |
Other | laravel | framework | e5bd04140d609964b10ff75d41ed101173a07f90.json | Add comments to all Lua scripts. | src/Illuminate/Queue/LuaScripts.php | @@ -7,6 +7,10 @@ class LuaScripts
/**
* Get the Lua script for computing the size of queue.
*
+ * KEYS[1] - The name of the primary queue
+ * KEYS[2] - The name of the "delayed" queue
+ * KEYS[3] - The name of the "reserved" queue
+ *
* @return string
*/
public static function size()
@@ -19,33 +23,50 @@ public static function size()
/**
* Get the Lua script for popping the next job off of the queue.
*
+ * KEYS[1] - The queue to pop jobs from, for example: queues:foo
+ * KEYS[2] - The queue to place reserved jobs on, for example: queues:foo:reserved
+ * ARGV[1] - The time at which the reserved job will expire
+ *
* @return string
*/
public static function pop()
{
return <<<'LUA'
+-- Pop the first job off of the queue...
local job = redis.call('lpop', KEYS[1])
local reserved = false
+
if(job ~= false) then
+ -- Increment the attempt count and place job on the reserved queue...
reserved = cjson.decode(job)
reserved['attempts'] = reserved['attempts'] + 1
reserved = cjson.encode(reserved)
redis.call('zadd', KEYS[2], ARGV[1], reserved)
end
+
return {job, reserved}
LUA;
}
/**
* Get the Lua script for releasing reserved jobs.
*
+ * KEYS[1] - The "delayed" queue we release jobs onto, for example: queues:foo:delayed
+ * KEYS[2] - The queue the jobs are currently on, for example: queues:foo:reserved
+ * ARGV[1] - The raw payload of the job to add to the "delayed" queue
+ * ARGV[2] - The UNIX timestamp at which the job should become available
+ *
* @return string
*/
public static function release()
{
return <<<'LUA'
+-- Remove the job from the current queue...
redis.call('zrem', KEYS[2], ARGV[1])
+
+-- Add the job onto the "delayed" queue...
redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
+
return true
LUA;
}
@@ -62,6 +83,7 @@ public static function release()
public static function migrateExpiredJobs()
{
return <<<'LUA'
+-- Get all of the jobs with an expired "score"...
local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])
-- If we have values in the array, we will remove them from the first queue | false |
Other | laravel | framework | 7a0318ca268d8c60c37e156a601bf843d8864c55.json | Apply fixes from StyleCI (#17047) | src/Illuminate/Queue/DatabaseQueue.php | @@ -2,7 +2,6 @@
namespace Illuminate\Queue;
-use DateTime;
use Carbon\Carbon;
use Illuminate\Database\Connection;
use Illuminate\Queue\Jobs\DatabaseJob; | false |
Other | laravel | framework | 8e618d00d880f75e31230891a6461379eb704180.json | Apply fixes from StyleCI (#17045) | src/Illuminate/Queue/Queue.php | @@ -2,7 +2,6 @@
namespace Illuminate\Queue;
-use Illuminate\Support\Arr;
use Illuminate\Container\Container;
abstract class Queue | false |
Other | laravel | framework | 0143f32d5eacfe0b985588502fd94849289d8298.json | Remove setMeta function. | src/Illuminate/Queue/Queue.php | @@ -132,29 +132,6 @@ protected function createPlainPayload($job, $data)
return ['job' => $job, 'data' => $data];
}
- /**
- * Set additional meta on a payload string.
- *
- * @param string $payload
- * @param string $key
- * @param string $value
- * @return string
- *
- * @throws \Illuminate\Queue\InvalidPayloadException
- */
- // protected function setMeta($payload, $key, $value)
- // {
- // $payload = json_decode($payload, true);
-
- // $payload = json_encode(Arr::set($payload, $key, $value));
-
- // if (JSON_ERROR_NONE !== json_last_error()) {
- // throw new InvalidPayloadException;
- // }
-
- // return $payload;
- // }
-
/**
* Set the IoC container instance.
* | false |
Other | laravel | framework | 20541a6a62af1ed2f44fdee51043ffb4b739bdb8.json | Apply fixes from StyleCI (#17044) | src/Illuminate/Queue/Jobs/Job.php | @@ -2,7 +2,6 @@
namespace Illuminate\Queue\Jobs;
-use Illuminate\Support\Arr;
use Illuminate\Queue\CalculatesDelays;
abstract class Job | true |
Other | laravel | framework | 20541a6a62af1ed2f44fdee51043ffb4b739bdb8.json | Apply fixes from StyleCI (#17044) | src/Illuminate/Queue/Queue.php | @@ -3,7 +3,6 @@
namespace Illuminate\Queue;
use Illuminate\Support\Arr;
-use InvalidArgumentException;
use Illuminate\Container\Container;
abstract class Queue | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Contracts/Queue/Queue.php | @@ -64,6 +64,16 @@ public function later($delay, $job, $data = '', $queue = null);
*/
public function laterOn($queue, $delay, $job, $data = '');
+ /**
+ * Push an array of jobs onto the queue.
+ *
+ * @param array $jobs
+ * @param mixed $data
+ * @param string $queue
+ * @return mixed
+ */
+ public function bulk($jobs, $data = '', $queue = null);
+
/**
* Pop the next job off of the queue.
* | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Queue/InvalidPayloadException.php | @@ -0,0 +1,19 @@
+<?php
+
+namespace Illuminate\Queue;
+
+use InvalidArgumentException;
+
+class InvalidPayloadException extends InvalidArgumentException
+{
+ /**
+ * Create a new exception instance.
+ *
+ * @param string|null $message
+ * @return void
+ */
+ public function __construct($message = null)
+ {
+ parent::__construct($message ?: json_last_error());
+ }
+} | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Queue/Jobs/Job.php | @@ -58,22 +58,9 @@ public function fire()
{
$payload = $this->payload();
- list($class, $method) = $this->parseJob($payload['job']);
+ list($class, $method) = JobName::parse($payload['job']);
- $this->instance = $this->resolve($class);
-
- $this->instance->{$method}($this, $payload['data']);
- }
-
- /**
- * Resolve the given job handler.
- *
- * @param string $class
- * @return mixed
- */
- protected function resolve($class)
- {
- return $this->container->make($class);
+ ($this->instance = $this->resolve($class))->{$method}($this, $payload['data']);
}
/**
@@ -137,60 +124,22 @@ public function failed($e)
{
$payload = $this->payload();
- list($class, $method) = $this->parseJob($payload['job']);
+ list($class, $method) = JobName::parse($payload['job']);
- $this->instance = $this->resolve($class);
-
- if (method_exists($this->instance, 'failed')) {
+ if (method_exists($this->instance = $this->resolve($class), 'failed')) {
$this->instance->failed($payload['data'], $e);
}
}
/**
- * Parse the job declaration into class and method.
- *
- * @param string $job
- * @return array
- */
- protected function parseJob($job)
- {
- $segments = explode('@', $job);
-
- return count($segments) > 1 ? $segments : [$segments[0], 'fire'];
- }
-
- /**
- * Get the name of the queued job class.
+ * Resolve the given class.
*
- * @return string
- */
- public function getName()
- {
- return $this->payload()['job'];
- }
-
- /**
- * Get the resolved name of the queued job class.
- *
- * Resolves the name of "wrapped" jobs such as class-based handlers.
- *
- * @return string
+ * @param string $class
+ * @return mixed
*/
- public function resolveName()
+ protected function resolve($class)
{
- $name = $this->getName();
-
- $payload = $this->payload();
-
- if ($name === 'Illuminate\Queue\CallQueuedHandler@call') {
- return Arr::get($payload, 'data.commandName', $name);
- }
-
- if ($name === 'Illuminate\Events\CallQueuedHandler@call') {
- return $payload['data']['class'].'@'.$payload['data']['method'];
- }
-
- return $name;
+ return $this->container->make($class);
}
/**
@@ -223,6 +172,28 @@ public function timeout()
return array_get($this->payload(), 'timeout');
}
+ /**
+ * Get the name of the queued job class.
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->payload()['job'];
+ }
+
+ /**
+ * Get the resolved name of the queued job class.
+ *
+ * Resolves the name of "wrapped" jobs such as class-based handlers.
+ *
+ * @return string
+ */
+ public function resolveName()
+ {
+ return JobName::resolve($this->getName(), $this->payload());
+ }
+
/**
* Get the name of the connection the job belongs to.
* | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Queue/Jobs/JobName.php | @@ -0,0 +1,41 @@
+<?php
+
+namespace Illuminate\Queue\Jobs;
+
+use Illuminate\Support\Arr;
+
+class JobName
+{
+ /**
+ * Parse the given job name into a class / method array.
+ *
+ * @param string $job
+ * @return array
+ */
+ public static function parse($job)
+ {
+ $segments = explode('@', $job);
+
+ return count($segments) > 1 ? $segments : [$segments[0], 'fire'];
+ }
+
+ /**
+ * Get the resolved name of the queued job class.
+ *
+ * @param string $name
+ * @param array $payload
+ * @return string
+ */
+ public static function resolve($name, $payload)
+ {
+ if ($name === 'Illuminate\Queue\CallQueuedHandler@call') {
+ return Arr::get($payload, 'data.commandName', $name);
+ }
+
+ if ($name === 'Illuminate\Events\CallQueuedHandler@call') {
+ return $payload['data']['class'].'@'.$payload['data']['method'];
+ }
+
+ return $name;
+ }
+} | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Queue/Queue.php | @@ -74,31 +74,53 @@ public function bulk($jobs, $data = '', $queue = null)
* @param string $queue
* @return string
*
- * @throws \InvalidArgumentException
+ * @throws \Illuminate\Queue\InvalidPayloadException
*/
protected function createPayload($job, $data = '', $queue = null)
{
- if (is_object($job)) {
- $payload = json_encode([
- 'job' => 'Illuminate\Queue\CallQueuedHandler@call',
- 'maxTries' => isset($job->tries) ? $job->tries : null,
- 'timeout' => isset($job->timeout) ? $job->timeout : null,
- 'data' => [
- 'commandName' => get_class($job),
- 'command' => serialize(clone $job),
- ],
- ]);
- } else {
- $payload = json_encode($this->createPlainPayload($job, $data));
- }
+ $payload = json_encode($this->createPayloadArray($job, $data, $queue));
if (JSON_ERROR_NONE !== json_last_error()) {
- throw new InvalidArgumentException('Unable to create payload: '.json_last_error_msg());
+ throw new InvalidPayloadException;
}
return $payload;
}
+ /**
+ * Create a payload array from the given job and data.
+ *
+ * @param string $job
+ * @param mixed $data
+ * @param string $queue
+ * @return array
+ */
+ protected function createPayloadArray($job, $data = '', $queue = null)
+ {
+ return is_object($job)
+ ? $this->createObjectPayload($job)
+ : $this->createPlainPayload($job, $data);
+ }
+
+ /**
+ * Create a payload for an object-based queue handler.
+ *
+ * @param mixed $job
+ * @return array
+ */
+ protected function createObjectPayload($job)
+ {
+ return [
+ 'job' => 'Illuminate\Queue\CallQueuedHandler@call',
+ 'maxTries' => isset($job->tries) ? $job->tries : null,
+ 'timeout' => isset($job->timeout) ? $job->timeout : null,
+ 'data' => [
+ 'commandName' => get_class($job),
+ 'command' => serialize(clone $job),
+ ],
+ ];
+ }
+
/**
* Create a typical, "plain" queue payload array.
*
@@ -119,20 +141,20 @@ protected function createPlainPayload($job, $data)
* @param string $value
* @return string
*
- * @throws \InvalidArgumentException
+ * @throws \Illuminate\Queue\InvalidPayloadException
*/
- protected function setMeta($payload, $key, $value)
- {
- $payload = json_decode($payload, true);
+ // protected function setMeta($payload, $key, $value)
+ // {
+ // $payload = json_decode($payload, true);
- $payload = json_encode(Arr::set($payload, $key, $value));
+ // $payload = json_encode(Arr::set($payload, $key, $value));
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new InvalidArgumentException('Unable to create payload: '.json_last_error_msg());
- }
+ // if (JSON_ERROR_NONE !== json_last_error()) {
+ // throw new InvalidPayloadException;
+ // }
- return $payload;
- }
+ // return $payload;
+ // }
/**
* Set the IoC container instance. | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Queue/RedisQueue.php | @@ -195,13 +195,12 @@ public function migrateExpiredJobs($from, $to)
* @param string $queue
* @return string
*/
- protected function createPayload($job, $data = '', $queue = null)
+ protected function createPayloadArray($job, $data = '', $queue = null)
{
- $payload = $this->setMeta(
- parent::createPayload($job, $data), 'id', $this->getRandomId()
- );
-
- return $this->setMeta($payload, 'attempts', 1);
+ return array_merge(parent::createPayloadArray($job, $data, $queue), [
+ 'id' => $this->getRandomId(),
+ 'attempts' => 1,
+ ]);
}
/** | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | src/Illuminate/Redis/Connections/PhpRedisConnection.php | @@ -9,7 +9,7 @@ class PhpRedisConnection extends Connection
/**
* Create a new Predis connection.
*
- * @param \Predis\Client $client
+ * @param \Redis $client
* @return void
*/
public function __construct($client) | true |
Other | laravel | framework | e030231604479d0326ad9bfb56a2a36229d78ff4.json | Extract some queue logic. | tests/Queue/QueueDatabaseQueueUnitTest.php | @@ -76,20 +76,6 @@ public function testFailureToCreatePayloadFromArray()
]);
}
- public function testFailureToCreatePayloadAfterAddingMeta()
- {
- $this->expectException('InvalidArgumentException');
-
- $queue = $this->getMockForAbstractClass('Illuminate\Queue\Queue');
- $class = new ReflectionClass('Illuminate\Queue\Queue');
-
- $setMeta = $class->getMethod('setMeta');
- $setMeta->setAccessible(true);
- $setMeta->invokeArgs($queue, [
- json_encode(['valid']), 'key', "\xc3\x28",
- ]);
- }
-
public function testBulkBatchPushesOntoDatabase()
{
$database = m::mock('Illuminate\Database\Connection'); | true |
Other | laravel | framework | 6f4076a5d2789538a835f63c47c41dfa4845c7b5.json | Apply fixes from StyleCI (#17042) | src/Illuminate/Queue/Jobs/Job.php | @@ -2,8 +2,6 @@
namespace Illuminate\Queue\Jobs;
-use DateTime;
-use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Queue\CalculatesDelays;
| true |
Other | laravel | framework | 6f4076a5d2789538a835f63c47c41dfa4845c7b5.json | Apply fixes from StyleCI (#17042) | src/Illuminate/Queue/Queue.php | @@ -2,8 +2,6 @@
namespace Illuminate\Queue;
-use DateTime;
-use Carbon\Carbon;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Container\Container; | true |
Other | laravel | framework | f6dd1278132de95b18238f5bf3c1786cf1557ae2.json | Fix forloop compilation | src/Illuminate/View/Concerns/ManagesLoops.php | @@ -73,7 +73,8 @@ public function popLoop()
*/
public function getLastLoop()
{
- return $last = Arr::last($this->loopsStack) ? (object) $last : null;
+ return ($last = Arr::last($this->loopsStack)) ? (object) $last : null;
+
}
/** | false |
Other | laravel | framework | f1978c4c99e3b2edce33b22f383f0a9d3e47791a.json | Convert looping event into an object. | src/Illuminate/Queue/Events/Looping.php | @@ -0,0 +1,8 @@
+<?php
+
+namespace Illuminate\Queue\Events;
+
+class Looping
+{
+ //
+} | true |
Other | laravel | framework | f1978c4c99e3b2edce33b22f383f0a9d3e47791a.json | Convert looping event into an object. | src/Illuminate/Queue/QueueManager.php | @@ -82,7 +82,7 @@ public function exceptionOccurred($callback)
*/
public function looping($callback)
{
- $this->app['events']->listen('illuminate.queue.looping', $callback);
+ $this->app['events']->listen(Events\Looping::class, $callback);
}
/**
@@ -163,11 +163,11 @@ protected function resolve($name)
*/
protected function getConnector($driver)
{
- if (isset($this->connectors[$driver])) {
- return call_user_func($this->connectors[$driver]);
+ if (! isset($this->connectors[$driver])) {
+ throw new InvalidArgumentException("No connector for [$driver]");
}
- throw new InvalidArgumentException("No connector for [$driver]");
+ return call_user_func($this->connectors[$driver]);
}
/**
@@ -202,11 +202,11 @@ public function addConnector($driver, Closure $resolver)
*/
protected function getConfig($name)
{
- if (is_null($name) || $name === 'null') {
- return ['driver' => 'null'];
+ if (! is_null($name) && $name !== 'null') {
+ return $this->app['config']["queue.connections.{$name}"];
}
- return $this->app['config']["queue.connections.{$name}"];
+ return ['driver' => 'null'];
}
/** | true |
Other | laravel | framework | f1978c4c99e3b2edce33b22f383f0a9d3e47791a.json | Convert looping event into an object. | src/Illuminate/Queue/Worker.php | @@ -125,7 +125,7 @@ protected function registerTimeoutHandler($job, WorkerOptions $options)
protected function daemonShouldRun(WorkerOptions $options)
{
if (($this->manager->isDownForMaintenance() && ! $options->force) ||
- $this->events->until('illuminate.queue.looping') === false) {
+ $this->events->until(new Events\Looping) === false) {
// If the application is down for maintenance or doesn't want the queues to run
// we will sleep for one second just in case the developer has it set to not
// sleep at all. This just prevents CPU from maxing out in this situation. | true |
Other | laravel | framework | 155aab1471634d70c622f755c04f90481595b5bb.json | Apply fixes from StyleCI (#17033) | src/Illuminate/Queue/InteractsWithQueue.php | @@ -2,8 +2,6 @@
namespace Illuminate\Queue;
-use Illuminate\Container\Container;
-use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Queue\Job as JobContract;
trait InteractsWithQueue | false |
Other | laravel | framework | 55afe12977b55dbafda940e18102bb52276ca569.json | Extract duplicate code which handles job failing. | src/Illuminate/Queue/FailingJob.php | @@ -0,0 +1,48 @@
+<?php
+
+namespace Illuminate\Queue;
+
+use Illuminate\Container\Container;
+use Illuminate\Queue\Events\JobFailed;
+use Illuminate\Contracts\Events\Dispatcher;
+
+class FailingJob
+{
+ /**
+ * Delete the given job, call the "failed" method, and raise the failed job event.
+ *
+ * @param string $connectionName
+ * @param \Illuminate\Queue\Jobs\Job $job
+ * @param \Exception $e
+ * @return void
+ */
+ public static function handle($connectionName, $job, $e = null)
+ {
+ if ($job->isDeleted()) {
+ return;
+ }
+
+ try {
+ // If the job has failed, we will delete it, call the "failed" method and then call
+ // an event indicating the job has failed so it can be logged if needed. This is
+ // to allow every developer to better keep monitor of their failed queue jobs.
+ $job->delete();
+
+ $job->failed($e);
+ } finally {
+ static::events()->fire(new JobFailed(
+ $connectionName, $job, $e ?: new ManuallyFailedException
+ ));
+ }
+ }
+
+ /**
+ * Get the event dispatcher instance.
+ *
+ * @return \Illuminate\Contracts\Events\Dispatcher
+ */
+ protected static function events()
+ {
+ return Container::getInstance()->make(Dispatcher::class);
+ }
+} | true |
Other | laravel | framework | 55afe12977b55dbafda940e18102bb52276ca569.json | Extract duplicate code which handles job failing. | src/Illuminate/Queue/InteractsWithQueue.php | @@ -45,18 +45,8 @@ public function delete()
*/
public function fail($exception = null)
{
- if (! $this->job || $this->job->isDeleted()) {
- return;
- }
-
- try {
- $this->job->delete();
-
- $this->job->failed($e);
- } finally {
- Container::getInstance()->make(Dispatcher::class)->fire(new Events\JobFailed(
- $this->job->getConnectionName(), $this->job, $exception ?: new ManuallyFailedException
- ));
+ if ($this->job) {
+ FailingJob::handle($this->job->getConnectionName(), $this->job, $exception);
}
}
| true |
Other | laravel | framework | 55afe12977b55dbafda940e18102bb52276ca569.json | Extract duplicate code which handles job failing. | src/Illuminate/Queue/Worker.php | @@ -324,29 +324,14 @@ protected function markJobAsFailedIfHasExceededMaxAttempts(
/**
* Mark the given job as failed and raise the relevant event.
*
- * Note: Any change to this method should also be made to InteractsWithQueue.
- *
* @param string $connectionName
* @param \Illuminate\Contracts\Queue\Job $job
* @param \Exception $e
* @return void
*/
protected function failJob($connectionName, $job, $e)
{
- if ($job->isDeleted()) {
- return;
- }
-
- try {
- // If the job has failed, we will delete it, call the "failed" method and then call
- // an event indicating the job has failed so it can be logged if needed. This is
- // to allow every developer to better keep monitor of their failed queue jobs.
- $job->delete();
-
- $job->failed($e);
- } finally {
- $this->raiseFailedJobEvent($connectionName, $job, $e);
- }
+ return FailingJob::handle($connectionName, $job, $e);
}
/** | true |
Other | laravel | framework | 55afe12977b55dbafda940e18102bb52276ca569.json | Extract duplicate code which handles job failing. | tests/Queue/QueueWorkerTest.php | @@ -1,5 +1,6 @@
<?php
+use Illuminate\Container\Container;
use Illuminate\Queue\WorkerOptions;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\JobProcessed;
@@ -14,10 +15,20 @@ class QueueWorkerTest extends PHPUnit_Framework_TestCase
public $events;
public $exceptionHandler;
- public function __construct()
+ public function setUp()
{
$this->events = Mockery::spy(Dispatcher::class);
$this->exceptionHandler = Mockery::spy(ExceptionHandler::class);
+
+ Container::setInstance($container = new Container);
+
+ $container->instance(Dispatcher::class, $this->events);
+ $container->instance(ExceptionHandler::class, $this->exceptionHandler);
+ }
+
+ public function tearDown()
+ {
+ Container::setInstance();
}
public function test_job_can_be_fired()
@@ -115,6 +126,7 @@ public function test_job_is_failed_if_it_has_already_exceeded_max_attempts()
$job = new WorkerFakeJob(function ($job) {
$job->attempts++;
});
+
$job->attempts = 2;
$worker = $this->getWorker('default', ['queue' => [$job]]);
@@ -167,6 +179,7 @@ private function workerDependencies($connectionName = 'default', $jobs = [])
private function workerOptions(array $overrides = [])
{
$options = new WorkerOptions;
+
foreach ($overrides as $key => $value) {
$options->{$key} = $value;
} | true |
Other | laravel | framework | 804c60cd8ad8de8c9ba32baa48ea51db38e3b295.json | Reset test variable
This doesn’t get reset before the test so every time `testExtendIsLazyInitialized` runs after the first time it fails. | tests/Container/ContainerTest.php | @@ -197,6 +197,8 @@ public function testExtendInstancesArePreserved()
public function testExtendIsLazyInitialized()
{
+ ContainerLazyExtendStub::$initialized = false;
+
$container = new Container;
$container->bind('ContainerLazyExtendStub');
$container->extend('ContainerLazyExtendStub', function ($obj, $container) { | false |
Other | laravel | framework | d88b4c7374b8caf0c7eccafe7fdc5e15bfb6b7c8.json | update PhpDoc return values (#17024) | src/Illuminate/Foundation/Auth/ResetsPasswords.php | @@ -31,7 +31,7 @@ public function showResetForm(Request $request, $token = null)
* Reset the given user's password.
*
* @param \Illuminate\Http\Request $request
- * @return \Illuminate\Http\Response
+ * @return \Illuminate\Http\RedirectResponse
*/
public function reset(Request $request)
{
@@ -112,7 +112,7 @@ protected function resetPassword($user, $password)
* Get the response for a successful password reset.
*
* @param string $response
- * @return \Illuminate\Http\Response
+ * @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetResponse($response)
{ | true |
Other | laravel | framework | d88b4c7374b8caf0c7eccafe7fdc5e15bfb6b7c8.json | update PhpDoc return values (#17024) | src/Illuminate/Foundation/Auth/SendsPasswordResetEmails.php | @@ -43,7 +43,7 @@ public function sendResetLinkEmail(Request $request)
* Get the response for a successful password reset link.
*
* @param string $response
- * @return \Illuminate\Http\Response
+ * @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkResponse($response)
{ | true |
Other | laravel | framework | 192fd8a0c5fef52ceb2af2e9dffe0fcd4bdcea63.json | Apply fixes from StyleCI (#17012) | src/Illuminate/View/Compilers/BladeCompiler.php | @@ -4,7 +4,6 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
-use Illuminate\View\Factory as ViewFactory;
class BladeCompiler extends Compiler implements CompilerInterface
{ | false |
Other | laravel | framework | fdeb01e367ba299e7f5e5accc733c2472b951f7e.json | Apply fixes from StyleCI (#17008) | src/Illuminate/Support/MessageBag.php | @@ -4,7 +4,6 @@
use Countable;
use JsonSerializable;
-use Illuminate\Support\Arr;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\MessageProvider; | false |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Cookie/CookieJar.php | @@ -21,7 +21,7 @@ class CookieJar implements JarContract
*
* @var string
*/
- protected $domain = null;
+ protected $domain;
/**
* The default secure setting (defaults to false). | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Foundation/Application.php | @@ -130,7 +130,7 @@ class Application extends Container implements ApplicationContract, HttpKernelIn
*
* @var string
*/
- protected $namespace = null;
+ protected $namespace;
/**
* Create a new Illuminate application instance. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Notifications/Messages/MailMessage.php | @@ -68,7 +68,7 @@ class MailMessage extends SimpleMessage
*
* @var int
*/
- public $priority = null;
+ public $priority;
/**
* Set the view for the mail message. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Notifications/Messages/SimpleMessage.php | @@ -23,9 +23,9 @@ class SimpleMessage
/**
* The notification's greeting.
*
- * @var string|null
+ * @var string
*/
- public $greeting = null;
+ public $greeting;
/**
* The "intro" lines of the notification. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Notifications/SendQueuedNotifications.php | @@ -29,7 +29,7 @@ class SendQueuedNotifications implements ShouldQueue
*
* @var array
*/
- protected $channels = null;
+ protected $channels;
/**
* Create a new job instance. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Pagination/AbstractPaginator.php | @@ -50,7 +50,7 @@ abstract class AbstractPaginator implements Htmlable
*
* @var string|null
*/
- protected $fragment = null;
+ protected $fragment;
/**
* The query string variable used to store the page. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | src/Illuminate/Validation/DatabasePresenceVerifier.php | @@ -20,7 +20,7 @@ class DatabasePresenceVerifier implements PresenceVerifierInterface
*
* @var string
*/
- protected $connection = null;
+ protected $connection;
/**
* Create a new database presence verifier. | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | tests/Database/DatabaseEloquentBelongsToTest.php | @@ -142,5 +142,5 @@ class AnotherEloquentBelongsToModelStub extends Illuminate\Database\Eloquent\Mod
class MissingEloquentBelongsToModelStub extends Illuminate\Database\Eloquent\Model
{
- public $foreign_key = null;
+ public $foreign_key;
} | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | tests/Mail/MailSesTransportTest.php | @@ -64,7 +64,7 @@ public function testSend()
class sendRawEmailMock
{
- protected $getResponse = null;
+ protected $getResponse;
public function __construct($responseValue)
{ | true |
Other | laravel | framework | c4da7b11df210e79c3156fff648768e5bac79825.json | Use implicit null instead of explicit (#16968) | tests/Queue/QueueWorkerTest.php | @@ -164,7 +164,7 @@ private function workerOptions(array $overrides = [])
*/
class InsomniacWorker extends Illuminate\Queue\Worker
{
- public $sleptFor = null;
+ public $sleptFor;
public function sleep($seconds)
{ | true |
Other | laravel | framework | 8a39838353ccd460a93252b9c7c114e9790d24a7.json | Apply fixes from StyleCI (#16965) | src/Illuminate/Support/Testing/Fakes/MailFake.php | @@ -2,8 +2,6 @@
namespace Illuminate\Support\Testing\Fakes;
-use Illuminate\Support\Collection;
-use Illuminate\Container\Container;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Mail\Mailable;
use PHPUnit_Framework_Assert as PHPUnit; | false |
Other | laravel | framework | b1d8f813d13960096493f3adc3bc32ace66ba2e6.json | Refactor the mail fake to not be really stupid.
Now it works more similarly to the other fakes and you can just use
$mailable->hasTo ->hasCc, etc. to make sure it has a given recipient
within your passed callable. The callable simply receives the mailable
instance. Properties on mailable are public for easy inspection. | src/Illuminate/Support/Testing/Fakes/MailFake.php | @@ -32,68 +32,6 @@ public function assertSent($mailable, $callback = null)
);
}
- /**
- * Assert if a mailable was sent based on a truth-test callback.
- *
- * @param mixed $users
- * @param string $mailable
- * @param callable|null $callback
- * @return void
- */
- public function assertSentTo($users, $mailable, $callback = null)
- {
- $users = $this->formatRecipients($users);
-
- return $this->assertSent($mailable, function ($mailable, $to) use ($users, $callback) {
- if (! $this->recipientsMatch($users, $this->formatRecipients($to))) {
- return false;
- }
-
- if (! is_null($callback)) {
- return $callback(...func_get_args());
- }
-
- return true;
- });
- }
-
- /**
- * Format the recipients into a collection.
- *
- * @param mixed $recipients
- * @return \Illuminate\Support\Collection
- */
- protected function formatRecipients($recipients)
- {
- if ($recipients instanceof Collection) {
- return $recipients;
- }
-
- return collect(is_array($recipients) ? $recipients : [$recipients]);
- }
-
- /**
- * Determine if two given recipient lists match.
- *
- * @param \Illuminate\Support\Collection $expected
- * @param \Illuminate\Support\Collection $recipients
- * @return bool
- */
- protected function recipientsMatch($expected, $recipients)
- {
- $expected = $expected->map(function ($expected) {
- return is_object($expected) ? $expected->email : $expected;
- });
-
- return $recipients->map(function ($recipient) {
- if (is_array($recipient)) {
- return $recipient['email'];
- }
-
- return is_object($recipient) ? $recipient->email : $recipient;
- })->diff($expected)->count() === 0;
- }
-
/**
* Determine if a mailable was sent based on a truth-test callback.
*
@@ -127,7 +65,7 @@ public function sent($mailable, $callback = null)
};
return $this->mailablesOf($mailable)->filter(function ($mailable) use ($callback) {
- return $callback($mailable->mailable, ...array_values($mailable->getRecipients()));
+ return $callback($mailable);
});
}
@@ -150,8 +88,8 @@ public function hasSent($mailable)
*/
protected function mailablesOf($type)
{
- return collect($this->mailables)->filter(function ($m) use ($type) {
- return $m->mailable instanceof $type;
+ return collect($this->mailables)->filter(function ($mailable) use ($type) {
+ return $mailable instanceof $type;
});
}
@@ -163,9 +101,7 @@ protected function mailablesOf($type)
*/
public function to($users)
{
- $this->mailables[] = $mailable = (new PendingMailFake)->to($users);
-
- return $mailable;
+ return (new PendingMailFake($this))->to($users);
}
/**
@@ -176,9 +112,7 @@ public function to($users)
*/
public function bcc($users)
{
- $this->mailables[] = $mailable = (new PendingMailFake)->bcc($users);
-
- return $mailable;
+ return (new PendingMailFake($this))->bcc($users);
}
/**
@@ -207,35 +141,7 @@ public function send($view, array $data = [], $callback = null)
return;
}
- Container::getInstance()->call([$view, 'build']);
-
- $mailable = new PendingMailFake;
-
- $mailable->mailable = $view;
-
- if ($recipients = $view->to) {
- $mailable->to($recipients);
- }
-
- if ($recipients = $view->bcc) {
- $mailable->bcc($recipients);
- }
-
- if ($recipients = $view->cc) {
- $mailable->cc($recipients);
- }
-
- $this->mailables[] = $mailable;
- }
-
- /**
- * Get the array of failed recipients.
- *
- * @return array
- */
- public function failures()
- {
- //
+ $this->mailables[] = $view;
}
/**
@@ -251,4 +157,14 @@ public function queue($view, array $data = [], $callback = null, $queue = null)
{
$this->send($view);
}
+
+ /**
+ * Get the array of failed recipients.
+ *
+ * @return array
+ */
+ public function failures()
+ {
+ //
+ }
} | true |
Other | laravel | framework | b1d8f813d13960096493f3adc3bc32ace66ba2e6.json | Refactor the mail fake to not be really stupid.
Now it works more similarly to the other fakes and you can just use
$mailable->hasTo ->hasCc, etc. to make sure it has a given recipient
within your passed callable. The callable simply receives the mailable
instance. Properties on mailable are public for easy inspection. | src/Illuminate/Support/Testing/Fakes/PendingMailFake.php | @@ -7,21 +7,15 @@
class PendingMailFake extends PendingMail
{
- /**
- * The mailable instance.
- *
- * @var mixed
- */
- public $mailable;
-
/**
* Create a new instance.
*
+ * @param \Illuminate\Support\Testing\Fakes\MailFake
* @return void
*/
- public function __construct()
+ public function __construct($mailer)
{
- //
+ $this->mailer = $mailer;
}
/**
@@ -43,7 +37,7 @@ public function send(Mailable $mailable)
*/
public function sendNow(Mailable $mailable)
{
- $this->mailable = $mailable;
+ $this->mailer->send($this->fill($mailable));
}
/**
@@ -56,14 +50,4 @@ public function queue(Mailable $mailable)
{
return $this->sendNow($mailable);
}
-
- /**
- * Get the recipient information for the mailable.
- *
- * @return array
- */
- public function getRecipients()
- {
- return ['to' => $this->to, 'cc' => $this->cc, 'bcc' => $this->bcc];
- }
} | true |
Other | laravel | framework | c52e1a467345607926c9378fb2646f8ead6cc1a4.json | Test broken case. | src/Illuminate/Mail/Mailable.php | @@ -388,11 +388,7 @@ public function replyTo($address, $name = null)
*/
protected function setAddress($address, $name = null, $property = 'to')
{
- if (! is_array($address) && ! $address instanceof Collection) {
- $address = [$address];
- }
-
- foreach ($address as $recipient) {
+ foreach ($this->recipientToArray($address, $name) as $recipient) {
$recipient = $this->normalizeRecipient($recipient);
$this->{$property}[] = [
@@ -404,6 +400,22 @@ protected function setAddress($address, $name = null, $property = 'to')
return $this;
}
+ /**
+ * Convert the given recipient arguments to an array.
+ *
+ * @param object|array|string $address
+ * @param string|null $name
+ * @return array
+ */
+ protected function recipientToArray($address, $name)
+ {
+ if (! is_array($address) && ! $address instanceof Collection) {
+ $address = is_string($name) ? [['name' => $name, 'email' => $address]] : [$address];
+ }
+
+ return $address;
+ }
+
/**
* Convert the given recipient into an object.
* | true |
Other | laravel | framework | c52e1a467345607926c9378fb2646f8ead6cc1a4.json | Test broken case. | tests/Mail/MailMailableTest.php | @@ -10,6 +10,10 @@ public function testMailableSetsRecipientsCorrectly()
$mailable->to('taylor@laravel.com');
$this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
+ $mailable = new WelcomeMailableStub;
+ $mailable->to('taylor@laravel.com', 'Taylor Otwell');
+ $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
+
$mailable = new WelcomeMailableStub;
$mailable->to(['taylor@laravel.com']);
$this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to); | true |
Other | laravel | framework | 53675f12c79495abf7525731c1e784d02800c129.json | Apply fixes from StyleCI (#16963) | src/Illuminate/Mail/Mailable.php | @@ -397,7 +397,7 @@ protected function setAddress($address, $name = null, $property = 'to')
$this->{$property}[] = [
'name' => isset($recipient->name) ? $recipient->name : null,
- 'address' => $recipient->email
+ 'address' => $recipient->email,
];
}
| true |
Other | laravel | framework | 53675f12c79495abf7525731c1e784d02800c129.json | Apply fixes from StyleCI (#16963) | tests/Mail/MailMailableTest.php | @@ -15,7 +15,7 @@ public function testMailableSetsRecipientsCorrectly()
$this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
$mailable = new WelcomeMailableStub;
- $mailable->to([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);;
+ $mailable->to([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
$this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
$mailable = new WelcomeMailableStub;
@@ -30,7 +30,7 @@ public function testMailableSetsRecipientsCorrectly()
$mailable->to(collect([new MailableTestUserStub, new MailableTestUserStub]));
$this->assertEquals([
['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com'],
- ['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']
+ ['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com'],
], $mailable->to);
}
| true |
Other | laravel | framework | 364ea7b994dda8f2b408b675b8764a665b5672db.json | Remove assignment (#16957)
Left over from removal of normalize(). | src/Illuminate/Container/Container.php | @@ -337,7 +337,7 @@ public function extend($abstract, Closure $closure)
*/
public function instance($abstract, $instance)
{
- unset($this->aliases[$abstract = $abstract]);
+ unset($this->aliases[$abstract]);
// We'll check to determine if this type has been bound before, and if it has
// we will fire the rebound callbacks registered with the container and it | false |
Other | laravel | framework | 1c797153006a316c6345affbf5bb7ef123250e06.json | Apply fixes from StyleCI (#16952) | src/Illuminate/Session/Store.php | @@ -6,7 +6,6 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use SessionHandlerInterface;
-use InvalidArgumentException;
use Illuminate\Contracts\Session\Session;
use Symfony\Component\HttpFoundation\Request;
| false |
Other | laravel | framework | f49ea906ac371dc343c6d878f13796f08561cfb0.json | Apply fixes from StyleCI (#16951) | src/Illuminate/Session/DatabaseSessionHandler.php | @@ -107,8 +107,8 @@ public function read($sessionId)
*/
protected function expired($session)
{
- return (isset($session->last_activity) &&
- $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp());
+ return isset($session->last_activity) &&
+ $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp();
}
/**
@@ -141,7 +141,7 @@ protected function getDefaultPayload($data)
{
$payload = [
'payload' => base64_encode($data),
- 'last_activity' => Carbon::now()->getTimestamp()
+ 'last_activity' => Carbon::now()->getTimestamp(),
];
if (! $this->container) { | false |
Other | laravel | framework | 5c4541bc43f22b0d99c5cc6db38781060bff836f.json | Refactor the gate. | src/Illuminate/Auth/Access/Gate.php | @@ -64,7 +64,8 @@ class Gate implements GateContract
* @param array $afterCallbacks
* @return void
*/
- public function __construct(Container $container, callable $userResolver, array $abilities = [], array $policies = [], array $beforeCallbacks = [], array $afterCallbacks = [])
+ public function __construct(Container $container, callable $userResolver, array $abilities = [],
+ array $policies = [], array $beforeCallbacks = [], array $afterCallbacks = [])
{
$this->policies = $policies;
$this->container = $container;
@@ -225,7 +226,7 @@ public function authorize($ability, $arguments = [])
}
/**
- * Get the raw result for the given ability for the current user.
+ * Get the raw result from the authorization callback.
*
* @param string $ability
* @param array|mixed $arguments
@@ -239,10 +240,20 @@ protected function raw($ability, $arguments = [])
$arguments = is_array($arguments) ? $arguments : [$arguments];
- if (is_null($result = $this->callBeforeCallbacks($user, $ability, $arguments))) {
+ // First we will call the "before" callbacks for the Gate. If any of these give
+ // back a non-null response, we will immediately return that result in order
+ // to let the developers override all checks for some authorization cases.
+ $result = $this->callBeforeCallbacks(
+ $user, $ability, $arguments
+ );
+
+ if (is_null($result)) {
$result = $this->callAuthCallback($user, $ability, $arguments);
}
+ // After calling the authorization callback, we will call the "after" callbacks
+ // that are registered with the Gate, which allows a developer to do logging
+ // if that is required for this application. Then we'll return the result.
$this->callAfterCallbacks(
$user, $ability, $arguments, $result
);
@@ -313,9 +324,7 @@ protected function callAfterCallbacks($user, $ability, array $arguments, $result
protected function resolveAuthCallback($user, $ability, array $arguments)
{
if (isset($arguments[0])) {
- $policy = $this->getPolicyFor($arguments[0]);
-
- if ($policy !== null) {
+ if (! is_null($policy = $this->getPolicyFor($arguments[0]))) {
return $this->resolvePolicyCallback($user, $ability, $arguments, $policy);
}
}
@@ -329,6 +338,40 @@ protected function resolveAuthCallback($user, $ability, array $arguments)
}
}
+ /**
+ * Get a policy instance for a given class.
+ *
+ * @param object|string $class
+ * @return mixed
+ */
+ public function getPolicyFor($class)
+ {
+ if (is_object($class)) {
+ $class = get_class($class);
+ }
+
+ if (isset($this->policies[$class])) {
+ return $this->resolvePolicy($this->policies[$class]);
+ }
+
+ foreach ($this->policies as $expected => $policy) {
+ if (is_subclass_of($class, $expected)) {
+ return $this->resolvePolicy($policy);
+ }
+ }
+ }
+
+ /**
+ * Build a policy class instance of the given type.
+ *
+ * @param object|string $class
+ * @return mixed
+ */
+ public function resolvePolicy($class)
+ {
+ return $this->container->make($class);
+ }
+
/**
* Resolve the callback for a policy check.
*
@@ -341,66 +384,60 @@ protected function resolveAuthCallback($user, $ability, array $arguments)
protected function resolvePolicyCallback($user, $ability, array $arguments, $policy)
{
return function () use ($user, $ability, $arguments, $policy) {
- // If we receive a non-null result from the before method, we will return it
- // as the final result. This will allow developers to override the checks
- // in the policy to return a result for all rules defined in the class.
- if (method_exists($policy, 'before')) {
- if (! is_null($result = $policy->before($user, $ability, ...$arguments))) {
- return $result;
- }
+ // This callback will be responsible for calling the policy's before method and
+ // running this policy method if necessary. This is used to when objects are
+ // mapped to policy objects in the user's configurations or on this class.
+ $result = $this->callPolicyBefore(
+ $policy, $user, $ability, $arguments
+ );
+
+ // When we receive a non-null result from this before method, we will return it
+ // as the "final" results. This will allow developers to override the checks
+ // in this policy to return the result for all rules defined in the class.
+ if (! is_null($result)) {
+ return $result;
}
- if (strpos($ability, '-') !== false) {
- $ability = Str::camel($ability);
- }
+ $ability = $this->formatAbilityToMethod($ability);
- // If the first argument is a string, that means they are passing a class name
- // to the policy. We will remove the first argument from this argument list
- // because the policy already knows what type of models it can authorize.
+ // If this first argument is a string, that means they are passing a class name
+ // to the policy. We will remove the first argument from this argument array
+ // because this policy already knows what type of models it can authorize.
if (isset($arguments[0]) && is_string($arguments[0])) {
array_shift($arguments);
}
- if (! is_callable([$policy, $ability])) {
- return false;
- }
-
- return $policy->{$ability}($user, ...$arguments);
+ return is_callable([$policy, $ability])
+ ? $policy->{$ability}($user, ...$arguments)
+ : false;
};
}
/**
- * Get a policy instance for a given class.
+ * Call the "before" method on the given policy, if applicable.
*
- * @param object|string $class
+ * @param mixed $policy
+ * @param \Illuminate\Contracts\Auth\Authenticatable $user
+ * @param string $ability
+ * @param array $arguments
* @return mixed
*/
- public function getPolicyFor($class)
+ protected function callPolicyBefore($policy, $user, $ability, $arguments)
{
- if (is_object($class)) {
- $class = get_class($class);
- }
-
- if (isset($this->policies[$class])) {
- return $this->resolvePolicy($this->policies[$class]);
- }
-
- foreach ($this->policies as $expected => $policy) {
- if (is_subclass_of($class, $expected)) {
- return $this->resolvePolicy($policy);
- }
+ if (method_exists($policy, 'before')) {
+ return $policy->before($user, $ability, ...$arguments);
}
}
/**
- * Build a policy class instance of the given type.
+ * Format the policy ability into a method name.
*
- * @param object|string $class
- * @return mixed
+ * @param string $ability
+ * @return string
*/
- public function resolvePolicy($class)
+ protected function formatAbilityToMethod($ability)
{
- return $this->container->make($class);
+ return strpos($ability, '-') !== false ? Str::camel($ability) : $ability;
}
/** | false |
Other | laravel | framework | d8ca3e632dbde7f8233463f330c4053f4fb08f3f.json | Add Macroable trait to RedirectResponse (#16929) | src/Illuminate/Http/RedirectResponse.php | @@ -6,14 +6,17 @@
use Illuminate\Support\Str;
use Illuminate\Support\MessageBag;
use Illuminate\Support\ViewErrorBag;
+use Illuminate\Support\Traits\Macroable;
use Illuminate\Session\Store as SessionStore;
use Illuminate\Contracts\Support\MessageProvider;
use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;
use Symfony\Component\HttpFoundation\RedirectResponse as BaseRedirectResponse;
class RedirectResponse extends BaseRedirectResponse
{
- use ResponseTrait;
+ use ResponseTrait, Macroable {
+ Macroable::__call as macroCall;
+ }
/**
* The request instance.
@@ -204,6 +207,10 @@ public function setSession(SessionStore $session)
*/
public function __call($method, $parameters)
{
+ if (static::hasMacro($method)) {
+ return $this->macroCall($method, $parameters);
+ }
+
if (Str::startsWith($method, 'with')) {
return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
} | false |
Other | laravel | framework | 7c2413712edcac15d82e1e9f359e8234788bf798.json | Apply fixes from StyleCI (#16942) | src/Illuminate/Container/Container.php | @@ -6,7 +6,6 @@
use ArrayAccess;
use LogicException;
use ReflectionClass;
-use ReflectionFunction;
use ReflectionParameter;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\Container as ContainerContract;
@@ -723,7 +722,7 @@ protected function resolveClass(ReflectionParameter $parameter)
}
/**
- * Throw an exception that the concrete is not instantiable
+ * Throw an exception that the concrete is not instantiable.
*
* @param string $concrete
* @return void | false |
Other | laravel | framework | 9165096f4458f8ab3cfbd4d6bd32479594a2161c.json | Apply fixes from StyleCI (#16940) | src/Illuminate/Container/Container.php | @@ -6,10 +6,8 @@
use ArrayAccess;
use LogicException;
use ReflectionClass;
-use ReflectionMethod;
use ReflectionFunction;
use ReflectionParameter;
-use InvalidArgumentException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\Container as ContainerContract;
| true |
Other | laravel | framework | 9165096f4458f8ab3cfbd4d6bd32479594a2161c.json | Apply fixes from StyleCI (#16940) | src/Illuminate/Container/MethodCaller.php | @@ -2,11 +2,8 @@
namespace Illuminate\Container;
-use LogicException;
-use ReflectionClass;
use ReflectionMethod;
use ReflectionFunction;
-use ReflectionParameter;
use InvalidArgumentException;
class MethodCaller | true |
Other | laravel | framework | 3be65cc66fe1fbee88ffb385e9468513c7592fa2.json | Apply fixes from StyleCI (#16939) | src/Illuminate/Console/Scheduling/Event.php | @@ -4,7 +4,6 @@
use Closure;
use Carbon\Carbon;
-use LogicException;
use Cron\CronExpression;
use GuzzleHttp\Client as HttpClient;
use Illuminate\Contracts\Mail\Mailer; | false |
Other | laravel | framework | efaffd58f5162fa45d2ca5bc352c4a568153ed57.json | Extract method on console parser. | src/Illuminate/Console/Parser.php | @@ -18,6 +18,25 @@ class Parser
* @throws \InvalidArgumentException
*/
public static function parse($expression)
+ {
+ $name = static::name($expression);
+
+ if (preg_match_all('/\{\s*(.*?)\s*\}/', $expression, $matches)) {
+ if (count($matches[1])) {
+ return array_merge([$name], static::parameters($matches[1]));
+ }
+ }
+
+ return [$name, [], []];
+ }
+
+ /**
+ * Extract the naem of the command from the expression.
+ *
+ * @param string $expression
+ * @return string
+ */
+ protected static function name($expression)
{
if (trim($expression) === '') {
throw new InvalidArgumentException('Console command definition is empty.');
@@ -27,17 +46,7 @@ public static function parse($expression)
throw new InvalidArgumentException('Unable to determine command name from signature.');
}
- $name = $matches[0];
-
- if (preg_match_all('/\{\s*(.*?)\s*\}/', $expression, $matches)) {
- $tokens = $matches[1];
-
- if (count($tokens)) {
- return array_merge([$name], static::parameters($tokens));
- }
- }
-
- return [$name, [], []];
+ return $matches[0];
}
/**
@@ -71,7 +80,7 @@ protected static function parameters(array $tokens)
*/
protected static function parseArgument($token)
{
- list($token, $description) = static::parseToken($token);
+ list($token, $description) = static::extractDescription($token);
switch (true) {
case Str::endsWith($token, '?*'):
@@ -95,7 +104,7 @@ protected static function parseArgument($token)
*/
protected static function parseOption($token)
{
- list($token, $description) = static::parseToken($token);
+ list($token, $description) = static::extractDescription($token);
$matches = preg_split('/\s*\|\s*/', $token, 2);
@@ -124,7 +133,7 @@ protected static function parseOption($token)
* @param string $token
* @return array
*/
- protected static function parseToken($token)
+ protected static function extractDescription($token)
{
$parts = preg_split('/\s+:\s+/', trim($token), 2);
| false |
Other | laravel | framework | b0370761de74571a793f40b0547b58402b9737d2.json | Refactor the generator command. | src/Illuminate/Console/GeneratorCommand.php | @@ -49,16 +49,22 @@ abstract protected function getStub();
*/
public function fire()
{
- $name = $this->parseName($this->getNameInput());
+ $name = $this->qualifyClass($this->getNameInput());
$path = $this->getPath($name);
+ // First we will check to see if the class already exists. If it does, we don't want
+ // to create the class and overwrite the user's code. So, we will bail out so the
+ // code is untouched. Otherwise, we will continue generating this class' files.
if ($this->alreadyExists($this->getNameInput())) {
$this->error($this->type.' already exists!');
return false;
}
+ // Next, we will generate the path to the location where this class' file should get
+ // written. Then, we will build the class and make the proper replacements on the
+ // stub files so that it gets the correctly formatted namespace and class name.
$this->makeDirectory($path);
$this->files->put($path, $this->buildClass($name));
@@ -67,61 +73,59 @@ public function fire()
}
/**
- * Determine if the class already exists.
+ * Parse the class name and format according to the root namespace.
*
- * @param string $rawName
- * @return bool
+ * @param string $name
+ * @return string
*/
- protected function alreadyExists($rawName)
+ protected function qualifyClass($name)
{
- $name = $this->parseName($rawName);
+ $rootNamespace = $this->rootNamespace();
- return $this->files->exists($this->getPath($name));
+ if (Str::startsWith($name, $rootNamespace)) {
+ return $name;
+ }
+
+ $name = str_replace('/', '\\', $name);
+
+ return $this->qualifyClass(
+ $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
+ );
}
/**
- * Get the destination class path.
+ * Get the default namespace for the class.
*
- * @param string $name
+ * @param string $rootNamespace
* @return string
*/
- protected function getPath($name)
+ protected function getDefaultNamespace($rootNamespace)
{
- $name = str_replace_first($this->rootNamespace(), '', $name);
-
- return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php';
+ return $rootNamespace;
}
/**
- * Parse the name and format according to the root namespace.
+ * Determine if the class already exists.
*
- * @param string $name
- * @return string
+ * @param string $rawName
+ * @return bool
*/
- protected function parseName($name)
+ protected function alreadyExists($rawName)
{
- $rootNamespace = $this->rootNamespace();
-
- if (Str::startsWith($name, $rootNamespace)) {
- return $name;
- }
-
- if (Str::contains($name, '/')) {
- $name = str_replace('/', '\\', $name);
- }
-
- return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name);
+ return $this->files->exists($this->getPath($this->qualifyClass($rawName)));
}
/**
- * Get the default namespace for the class.
+ * Get the destination class path.
*
- * @param string $rootNamespace
+ * @param string $name
* @return string
*/
- protected function getDefaultNamespace($rootNamespace)
+ protected function getPath($name)
{
- return $rootNamespace;
+ $name = str_replace_first($this->rootNamespace(), '', $name);
+
+ return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php';
}
/**
@@ -135,6 +139,8 @@ protected function makeDirectory($path)
if (! $this->files->isDirectory(dirname($path))) {
$this->files->makeDirectory(dirname($path), 0777, true, true);
}
+
+ return $path;
}
/**
@@ -160,18 +166,16 @@ protected function buildClass($name)
protected function replaceNamespace(&$stub, $name)
{
$stub = str_replace(
- 'DummyNamespace', $this->getNamespace($name), $stub
- );
-
- $stub = str_replace(
- 'DummyRootNamespace', $this->rootNamespace(), $stub
+ ['DummyNamespace', 'DummyRootNamespace'],
+ [$this->getNamespace($name), $this->rootNamespace()],
+ $stub
);
return $this;
}
/**
- * Get the full namespace name for a given class.
+ * Get the full namespace for a given class, without the class name.
*
* @param string $name
* @return string | true |
Other | laravel | framework | b0370761de74571a793f40b0547b58402b9737d2.json | Refactor the generator command. | src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php | @@ -84,12 +84,12 @@ protected function getPath($name)
}
/**
- * Parse the name and format according to the root namespace.
+ * Parse the class name and format according to the root namespace.
*
* @param string $name
* @return string
*/
- protected function parseName($name)
+ protected function qualifyClass($name)
{
return $name;
} | true |
Other | laravel | framework | f21ab706def178635410b2a17a9bee38e4bf2f9b.json | fix cluster resolution | src/Illuminate/Redis/Connectors/PhpRedisConnector.php | @@ -16,7 +16,7 @@ class PhpRedisConnector
* @param array $config
* @param array $clusterOptions
* @param array $options
- * @return \Illuminate\Redis\PredisConnection
+ * @return \Illuminate\Redis\PhpRedisConnection
*/
public function connect(array $config, array $options)
{
@@ -31,7 +31,7 @@ public function connect(array $config, array $options)
* @param array $config
* @param array $clusterOptions
* @param array $options
- * @return \Illuminate\Redis\PredisClusterConnection
+ * @return \Illuminate\Redis\PhpRedisClusterConnection
*/
public function connectToCluster(array $config, array $clusterOptions, array $options)
{ | true |
Other | laravel | framework | f21ab706def178635410b2a17a9bee38e4bf2f9b.json | fix cluster resolution | src/Illuminate/Redis/Connectors/PredisConnector.php | @@ -34,8 +34,10 @@ public function connect(array $config, array $options)
*/
public function connectToCluster(array $config, array $clusterOptions, array $options)
{
+ $clusterSpecificOptions = Arr::pull($config, 'options', []);
+
return new PredisClusterConnection(new Client(array_values($config), array_merge(
- $options, $clusterOptions, Arr::pull($config, 'options', [])
+ $options, $clusterOptions, $clusterSpecificOptions
)));
}
} | true |
Other | laravel | framework | f21ab706def178635410b2a17a9bee38e4bf2f9b.json | fix cluster resolution | src/Illuminate/Redis/RedisManager.php | @@ -85,7 +85,7 @@ protected function resolveCluster($name)
$clusterOptions = Arr::get($this->config, 'clusters.options', []);
return $this->connector()->connectToCluster(
- $this->config['clusters'][$name], $clusterOptions, $this->config
+ $this->config['clusters'][$name], $clusterOptions, Arr::get($this->config, 'options', [])
);
}
| true |
Other | laravel | framework | f7f13fab9a451bc2249fc0709b6cf1fa6b7c795a.json | remove unused method | src/Illuminate/Routing/RouteDependencyResolverTrait.php | @@ -9,20 +9,6 @@
trait RouteDependencyResolverTrait
{
- /**
- * Call a class method with the resolved dependencies.
- *
- * @param object $instance
- * @param string $method
- * @return mixed
- */
- protected function callWithDependencies($instance, $method)
- {
- return call_user_func_array(
- [$instance, $method], $this->resolveClassMethodDependencies([], $instance, $method)
- );
- }
-
/**
* Resolve the object method's type-hinted dependencies.
* | false |
Other | laravel | framework | 9111e0eaace063a96ff6321618bbf23e7267599e.json | Apply fixes from StyleCI (#16921) | src/Illuminate/Routing/UrlGenerator.php | @@ -3,13 +3,11 @@
namespace Illuminate\Routing;
use Closure;
-use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use InvalidArgumentException;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Routing\UrlRoutable;
-use Illuminate\Routing\Exceptions\UrlGenerationException;
use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
class UrlGenerator implements UrlGeneratorContract
@@ -387,7 +385,7 @@ protected function extractQueryString($path)
if (($queryPosition = strpos($path, '?')) !== false) {
return [
substr($path, 0, $queryPosition),
- substr($path, $queryPosition)
+ substr($path, $queryPosition),
];
}
| false |
Other | laravel | framework | 0f3e5092c0e9b9628da951107365fd4a0a3d741e.json | Apply fixes from StyleCI (#16913) | src/Illuminate/Routing/Router.php | @@ -12,7 +12,6 @@
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Routing\BindingRegistrar;
-use Illuminate\Database\Eloquent\ModelNotFoundException;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use Illuminate\Contracts\Routing\Registrar as RegistrarContract;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; | false |
Other | laravel | framework | dd58def4e5fca939c2f51fe58702a996ec29c520.json | Apply fixes from StyleCI (#16911) | src/Illuminate/Routing/Router.php | @@ -3,7 +3,6 @@
namespace Illuminate\Routing;
use Closure;
-use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Http\Response; | false |
Other | laravel | framework | b208a4fc3b35da167a2dcb9b581d9e072d20ec92.json | extract some classes for router | src/Illuminate/Routing/MiddlewareNameResolver.php | @@ -0,0 +1,85 @@
+<?php
+
+namespace Illuminate\Routing;
+
+use Closure;
+
+class MiddlewareNameResolver
+{
+ /**
+ * Resolve the middleware name to a class name(s) preserving passed parameters.
+ *
+ * @param string $name
+ * @param array $map
+ * @param array $middlewareGroups
+ * @return string|array
+ */
+ public static function resolve($name, $map, $middlewareGroups)
+ {
+ // When the middleware is simply a Closure, we will return this Closure instance
+ // directly so that Closures can be registered as middleware inline, which is
+ // convenient on occasions when the developers are experimenting with them.
+ if ($name instanceof Closure) {
+ return $name;
+ } elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
+ return $map[$name];
+
+ // If the middleware is the name of a middleware group, we will return the array
+ // of middlewares that belong to the group. This allows developers to group a
+ // set of middleware under single keys that can be conveniently referenced.
+ } elseif (isset($middlewareGroups[$name])) {
+ return static::parseMiddlewareGroup(
+ $name, $map, $middlewareGroups
+ );
+
+ // Finally, when the middleware is simply a string mapped to a class name the
+ // middleware name will get parsed into the full class name and parameters
+ // which may be run using the Pipeline which accepts this string format.
+ } else {
+ list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
+
+ return (isset($map[$name]) ? $map[$name] : $name).
+ (! is_null($parameters) ? ':'.$parameters : '');
+ }
+ }
+
+ /**
+ * Parse the middleware group and format it for usage.
+ *
+ * @param string $name
+ * @param array $middlewareGroups
+ * @return array
+ */
+ protected static function parseMiddlewareGroup($name, $map, $middlewareGroups)
+ {
+ $results = [];
+
+ foreach ($middlewareGroups[$name] as $middleware) {
+ // If the middleware is another middleware group we will pull in the group and
+ // merge its middleware into the results. This allows groups to conveniently
+ // reference other groups without needing to repeat all their middlewares.
+ if (isset($middlewareGroups[$middleware])) {
+ $results = array_merge($results, static::parseMiddlewareGroup(
+ $middleware, $map, $middlewareGroups
+ ));
+
+ continue;
+ }
+
+ list($middleware, $parameters) = array_pad(
+ explode(':', $middleware, 2), 2, null
+ );
+
+ // If this middleware is actually a route middleware, we will extract the full
+ // class name out of the middleware list now. Then we'll add the parameters
+ // back onto this class' name so the pipeline will properly extract them.
+ if (isset($map[$middleware])) {
+ $middleware = $map[$middleware];
+ }
+
+ $results[] = $middleware.($parameters ? ':'.$parameters : '');
+ }
+
+ return $results;
+ }
+} | true |
Other | laravel | framework | b208a4fc3b35da167a2dcb9b581d9e072d20ec92.json | extract some classes for router | src/Illuminate/Routing/RouteGroup.php | @@ -0,0 +1,95 @@
+<?php
+
+namespace Illuminate\Routing;
+
+use Illuminate\Support\Arr;
+
+class RouteGroup
+{
+ /**
+ * Merge route groups into a new array.
+ *
+ * @param array $new
+ * @param array $old
+ * @return array
+ */
+ public static function merge($new, $old)
+ {
+ if (isset($new['domain'])) {
+ unset($old['domain']);
+ }
+
+ $new = array_merge(static::formatAs($new, $old), [
+ 'namespace' => static::formatNamespace($new, $old),
+ 'prefix' => static::formatPrefix($new, $old),
+ 'where' => static::formatWhere($new, $old),
+ ]);
+
+ return array_merge_recursive(Arr::except(
+ $old, ['namespace', 'prefix', 'where', 'as']
+ ), $new);
+ }
+
+ /**
+ * Format the namespace for the new group attributes.
+ *
+ * @param array $new
+ * @param array $old
+ * @return string|null
+ */
+ protected static function formatNamespace($new, $old)
+ {
+ if (isset($new['namespace'])) {
+ return isset($old['namespace'])
+ ? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\')
+ : trim($new['namespace'], '\\');
+ }
+
+ return isset($old['namespace']) ? $old['namespace'] : null;
+ }
+
+ /**
+ * Format the prefix for the new group attributes.
+ *
+ * @param array $new
+ * @param array $old
+ * @return string|null
+ */
+ protected static function formatPrefix($new, $old)
+ {
+ $old = Arr::get($old, 'prefix');
+
+ return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;
+ }
+
+ /**
+ * Format the "wheres" for the new group attributes.
+ *
+ * @param array $new
+ * @param array $old
+ * @return array
+ */
+ protected static function formatWhere($new, $old)
+ {
+ return array_merge(
+ isset($old['where']) ? $old['where'] : [],
+ isset($new['where']) ? $new['where'] : []
+ );
+ }
+
+ /**
+ * Format the "as" clause of the new group attributes.
+ *
+ * @param array $new
+ * @param array $old
+ * @return array
+ */
+ protected static function formatAs($new, $old)
+ {
+ if (isset($old['as'])) {
+ $new['as'] = $old['as'].Arr::get($new, 'as', '');
+ }
+
+ return $new;
+ }
+} | true |
Other | laravel | framework | b208a4fc3b35da167a2dcb9b581d9e072d20ec92.json | extract some classes for router | src/Illuminate/Routing/Router.php | @@ -275,23 +275,6 @@ public function group(array $attributes, $routes)
array_pop($this->groupStack);
}
- /**
- * Load the provided routes.
- *
- * @param \Closure|string $routes
- * @return void
- */
- protected function loadRoutes($routes)
- {
- if ($routes instanceof Closure) {
- $routes($this);
- } else {
- $router = $this;
-
- require $routes;
- }
- }
-
/**
* Update the group stack with the given attributes.
*
@@ -301,7 +284,7 @@ protected function loadRoutes($routes)
protected function updateGroupStack(array $attributes)
{
if (! empty($this->groupStack)) {
- $attributes = $this->mergeGroup($attributes, end($this->groupStack));
+ $attributes = RouteGroup::merge($attributes, end($this->groupStack));
}
$this->groupStack[] = $attributes;
@@ -315,72 +298,24 @@ protected function updateGroupStack(array $attributes)
*/
public function mergeWithLastGroup($new)
{
- return $this->mergeGroup($new, end($this->groupStack));
- }
-
- /**
- * Merge the given group attributes.
- *
- * @param array $new
- * @param array $old
- * @return array
- */
- 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'] : [],
- isset($new['where']) ? $new['where'] : []
- );
-
- if (isset($old['as'])) {
- $new['as'] = $old['as'].(isset($new['as']) ? $new['as'] : '');
- }
-
- return array_merge_recursive(Arr::except($old, ['namespace', 'prefix', 'where', 'as']), $new);
+ return RouteGroup::merge($new, end($this->groupStack));
}
/**
- * Format the uses prefix for the new group attributes.
- *
- * @param array $new
- * @param array $old
- * @return string|null
- */
- protected static function formatUsesPrefix($new, $old)
- {
- if (isset($new['namespace'])) {
- return isset($old['namespace'])
- ? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\')
- : trim($new['namespace'], '\\');
- }
-
- return isset($old['namespace']) ? $old['namespace'] : null;
- }
-
- /**
- * Format the prefix for the new group attributes.
+ * Load the provided routes.
*
- * @param array $new
- * @param array $old
- * @return string|null
+ * @param \Closure|string $routes
+ * @return void
*/
- protected static function formatGroupPrefix($new, $old)
+ protected function loadRoutes($routes)
{
- $oldPrefix = isset($old['prefix']) ? $old['prefix'] : null;
+ if ($routes instanceof Closure) {
+ $routes($this);
+ } else {
+ $router = $this;
- if (isset($new['prefix'])) {
- return trim($oldPrefix, '/').'/'.trim($new['prefix'], '/');
+ require $routes;
}
-
- return $oldPrefix;
}
/**
@@ -445,6 +380,62 @@ protected function createRoute($methods, $uri, $action)
return $route;
}
+ /**
+ * Determine if the action is routing to a controller.
+ *
+ * @param array $action
+ * @return bool
+ */
+ protected function actionReferencesController($action)
+ {
+ if (! $action instanceof Closure) {
+ return is_string($action) || (isset($action['uses']) && is_string($action['uses']));
+ }
+
+ return false;
+ }
+
+ /**
+ * Add a controller based route action to the action array.
+ *
+ * @param array|string $action
+ * @return array
+ */
+ protected function convertToControllerAction($action)
+ {
+ if (is_string($action)) {
+ $action = ['uses' => $action];
+ }
+
+ // Here we'll merge any group "uses" statement if necessary so that the action
+ // has the proper clause for this property. Then we can simply set the name
+ // of the controller on the action and return the action array for usage.
+ if (! empty($this->groupStack)) {
+ $action['uses'] = $this->prependGroupNamespace($action['uses']);
+ }
+
+ // Here we will set this controller name on the action array just so we always
+ // have a copy of it for reference if we need it. This can be used while we
+ // search for a controller name or do some other type of fetch operation.
+ $action['controller'] = $action['uses'];
+
+ return $action;
+ }
+
+ /**
+ * Prepend the last group namespace onto the use clause.
+ *
+ * @param string $class
+ * @return string
+ */
+ protected function prependGroupNamespace($class)
+ {
+ $group = end($this->groupStack);
+
+ return isset($group['namespace']) && strpos($class, '\\') !== 0
+ ? $group['namespace'].'\\'.$class : $class;
+ }
+
/**
* Create a new Route object.
*
@@ -479,9 +470,9 @@ protected function prefix($uri)
*/
protected function addWhereClausesToRoute($route)
{
- $where = isset($route->getAction()['where']) ? $route->getAction()['where'] : [];
-
- $route->where(array_merge($this->patterns, $where));
+ $route->where(array_merge(
+ $this->patterns, isset($route->getAction()['where']) ? $route->getAction()['where'] : []
+ ));
return $route;
}
@@ -494,64 +485,7 @@ protected function addWhereClausesToRoute($route)
*/
protected function mergeGroupAttributesIntoRoute($route)
{
- $action = $this->mergeWithLastGroup($route->getAction());
-
- $route->setAction($action);
- }
-
- /**
- * Determine if the action is routing to a controller.
- *
- * @param array $action
- * @return bool
- */
- protected function actionReferencesController($action)
- {
- if ($action instanceof Closure) {
- return false;
- }
-
- return is_string($action) || (isset($action['uses']) && is_string($action['uses']));
- }
-
- /**
- * Add a controller based route action to the action array.
- *
- * @param array|string $action
- * @return array
- */
- protected function convertToControllerAction($action)
- {
- if (is_string($action)) {
- $action = ['uses' => $action];
- }
-
- // Here we'll merge any group "uses" statement if necessary so that the action
- // has the proper clause for this property. Then we can simply set the name
- // of the controller on the action and return the action array for usage.
- if (! empty($this->groupStack)) {
- $action['uses'] = $this->prependGroupUses($action['uses']);
- }
-
- // Here we will set this controller name on the action array just so we always
- // have a copy of it for reference if we need it. This can be used while we
- // search for a controller name or do some other type of fetch operation.
- $action['controller'] = $action['uses'];
-
- return $action;
- }
-
- /**
- * Prepend the last group uses onto the use clause.
- *
- * @param string $uses
- * @return string
- */
- protected function prependGroupUses($uses)
- {
- $group = end($this->groupStack);
-
- return isset($group['namespace']) && strpos($uses, '\\') !== 0 ? $group['namespace'].'\\'.$uses : $uses;
+ $route->setAction($this->mergeWithLastGroup($route->getAction()));
}
/**
@@ -591,6 +525,21 @@ public function dispatchToRoute(Request $request)
return $this->prepareResponse($request, $response);
}
+ /**
+ * Find the route matching a given request.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @return \Illuminate\Routing\Route
+ */
+ protected function findRoute($request)
+ {
+ $this->current = $route = $this->routes->match($request);
+
+ $this->container->instance('Illuminate\Routing\Route', $route);
+
+ return $route;
+ }
+
/**
* Run the given route within a Stack "onion" instance.
*
@@ -616,94 +565,20 @@ protected function runRouteWithinStack(Route $route, Request $request)
}
/**
- * Gather the middleware for the given route.
+ * Gather the middleware for the given route with resolved class names.
*
* @param \Illuminate\Routing\Route $route
* @return array
*/
public function gatherRouteMiddleware(Route $route)
{
$middleware = collect($route->gatherMiddleware())->map(function ($name) {
- return (array) $this->resolveMiddlewareClassName($name);
+ return (array) MiddlewareNameResolver::resolve($name, $this->middleware, $this->middlewareGroups);
})->flatten();
return $this->sortMiddleware($middleware);
}
- /**
- * Resolve the middleware name to a class name(s) preserving passed parameters.
- *
- * @param string $name
- * @return string|array
- */
- public function resolveMiddlewareClassName($name)
- {
- $map = $this->middleware;
-
- // When the middleware is simply a Closure, we will return this Closure instance
- // directly so that Closures can be registered as middleware inline, which is
- // convenient on occasions when the developers are experimenting with them.
- if ($name instanceof Closure) {
- return $name;
- } elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
- return $map[$name];
-
- // If the middleware is the name of a middleware group, we will return the array
- // of middlewares that belong to the group. This allows developers to group a
- // set of middleware under single keys that can be conveniently referenced.
- } elseif (isset($this->middlewareGroups[$name])) {
- return $this->parseMiddlewareGroup($name);
-
- // Finally, when the middleware is simply a string mapped to a class name the
- // middleware name will get parsed into the full class name and parameters
- // which may be run using the Pipeline which accepts this string format.
- } else {
- list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
-
- return (isset($map[$name]) ? $map[$name] : $name).
- (! is_null($parameters) ? ':'.$parameters : '');
- }
- }
-
- /**
- * Parse the middleware group and format it for usage.
- *
- * @param string $name
- * @return array
- */
- protected function parseMiddlewareGroup($name)
- {
- $results = [];
-
- foreach ($this->middlewareGroups[$name] as $middleware) {
- // If the middleware is another middleware group we will pull in the group and
- // merge its middleware into the results. This allows groups to conveniently
- // reference other groups without needing to repeat all their middlewares.
- if (isset($this->middlewareGroups[$middleware])) {
- $results = array_merge(
- $results, $this->parseMiddlewareGroup($middleware)
- );
-
- continue;
- }
-
- list($middleware, $parameters) = array_pad(
- explode(':', $middleware, 2), 2, null
- );
-
- // If this middleware is actually a route middleware, we will extract the full
- // class name out of the middleware list now. Then we'll add the parameters
- // back onto this class' name so the pipeline will properly extract them.
- if (isset($this->middleware[$middleware])) {
- $middleware = $this->middleware[$middleware];
- }
-
- $results[] = $middleware.($parameters ? ':'.$parameters : '');
- }
-
- return $results;
- }
-
/**
* Sort the given middleware by priority.
*
@@ -716,18 +591,21 @@ protected function sortMiddleware(Collection $middlewares)
}
/**
- * Find the route matching a given request.
+ * Create a response instance from the given value.
*
- * @param \Illuminate\Http\Request $request
- * @return \Illuminate\Routing\Route
+ * @param \Symfony\Component\HttpFoundation\Request $request
+ * @param mixed $response
+ * @return \Illuminate\Http\Response
*/
- protected function findRoute($request)
+ public function prepareResponse($request, $response)
{
- $this->current = $route = $this->routes->match($request);
-
- $this->container->instance('Illuminate\Routing\Route', $route);
+ if ($response instanceof PsrResponseInterface) {
+ $response = (new HttpFoundationFactory)->createResponse($response);
+ } elseif (! $response instanceof SymfonyResponse) {
+ $response = new Response($response);
+ }
- return $route;
+ return $response->prepare($request);
}
/**
@@ -926,19 +804,6 @@ public function bind($key, $binder)
$this->binders[str_replace('-', '_', $key)] = $binder;
}
- /**
- * Get the binding callback for a given binding.
- *
- * @param string $key
- * @return \Closure|null
- */
- public function getBindingCallback($key)
- {
- if (isset($this->binders[$key = str_replace('-', '_', $key)])) {
- return $this->binders[$key];
- }
- }
-
/**
* Create a class based binding using the IoC container.
*
@@ -961,6 +826,29 @@ public function createClassBinding($binding)
};
}
+ /**
+ * Get the binding callback for a given binding.
+ *
+ * @param string $key
+ * @return \Closure|null
+ */
+ public function getBindingCallback($key)
+ {
+ if (isset($this->binders[$key = str_replace('-', '_', $key)])) {
+ return $this->binders[$key];
+ }
+ }
+
+ /**
+ * Get the global "where" patterns.
+ *
+ * @return array
+ */
+ public function getPatterns()
+ {
+ return $this->patterns;
+ }
+
/**
* Set a global where pattern on all routes.
*
@@ -986,24 +874,6 @@ public function patterns($patterns)
}
}
- /**
- * Create a response instance from the given value.
- *
- * @param \Symfony\Component\HttpFoundation\Request $request
- * @param mixed $response
- * @return \Illuminate\Http\Response
- */
- public function prepareResponse($request, $response)
- {
- if ($response instanceof PsrResponseInterface) {
- $response = (new HttpFoundationFactory)->createResponse($response);
- } elseif (! $response instanceof SymfonyResponse) {
- $response = new Response($response);
- }
-
- return $response->prepare($request);
- }
-
/**
* Determine if the router currently has a group stack.
*
@@ -1240,16 +1110,6 @@ public function setRoutes(RouteCollection $routes)
$this->container->instance('routes', $this->routes);
}
- /**
- * Get the global "where" patterns.
- *
- * @return array
- */
- public function getPatterns()
- {
- return $this->patterns;
- }
-
/**
* Dynamically handle calls into the router instance.
* | true |
Other | laravel | framework | b208a4fc3b35da167a2dcb9b581d9e072d20ec92.json | extract some classes for router | tests/Routing/RoutingRouteTest.php | @@ -5,6 +5,7 @@
use Illuminate\Routing\Router;
use Illuminate\Events\Dispatcher;
use Illuminate\Routing\Controller;
+use Illuminate\Routing\RouteGroup;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Middleware\Authorize;
@@ -694,23 +695,23 @@ public function testModelBindingThroughIOC()
public function testGroupMerging()
{
$old = ['prefix' => 'foo/bar/'];
- $this->assertEquals(['prefix' => 'foo/bar/baz', 'namespace' => null, 'where' => []], Router::mergeGroup(['prefix' => 'baz'], $old));
+ $this->assertEquals(['prefix' => 'foo/bar/baz', 'namespace' => null, 'where' => []], RouteGroup::merge(['prefix' => 'baz'], $old));
$old = ['domain' => 'foo'];
- $this->assertEquals(['domain' => 'baz', 'prefix' => null, 'namespace' => null, 'where' => []], Router::mergeGroup(['domain' => 'baz'], $old));
+ $this->assertEquals(['domain' => 'baz', 'prefix' => null, 'namespace' => null, 'where' => []], RouteGroup::merge(['domain' => 'baz'], $old));
$old = ['as' => 'foo.'];
- $this->assertEquals(['as' => 'foo.bar', 'prefix' => null, 'namespace' => null, 'where' => []], Router::mergeGroup(['as' => 'bar'], $old));
+ $this->assertEquals(['as' => 'foo.bar', 'prefix' => null, 'namespace' => null, 'where' => []], RouteGroup::merge(['as' => 'bar'], $old));
$old = ['where' => ['var1' => 'foo', 'var2' => 'bar']];
$this->assertEquals(['prefix' => null, 'namespace' => null, 'where' => [
'var1' => 'foo', 'var2' => 'baz', 'var3' => 'qux',
- ]], Router::mergeGroup(['where' => ['var2' => 'baz', 'var3' => 'qux']], $old));
+ ]], RouteGroup::merge(['where' => ['var2' => 'baz', 'var3' => 'qux']], $old));
$old = [];
$this->assertEquals(['prefix' => null, 'namespace' => null, 'where' => [
'var1' => 'foo', 'var2' => 'bar',
- ]], Router::mergeGroup(['where' => ['var1' => 'foo', 'var2' => 'bar']], $old));
+ ]], RouteGroup::merge(['where' => ['var1' => 'foo', 'var2' => 'bar']], $old));
}
public function testRouteGrouping() | true |
Other | laravel | framework | eecf6eca8b4a0cfdf8ec2b0148ee726b8b67c6bb.json | Start organizing router. | src/Illuminate/Routing/Router.php | @@ -123,10 +123,6 @@ public function __construct(Dispatcher $events, Container $container = null)
$this->events = $events;
$this->routes = new RouteCollection;
$this->container = $container ?: new Container;
-
- $this->bind('_missing', function ($v) {
- return explode('/', $v);
- });
}
/**
@@ -228,39 +224,6 @@ public function match($methods, $uri, $action = null)
return $this->addRoute(array_map('strtoupper', (array) $methods), $uri, $action);
}
- /**
- * Set the unmapped global resource parameters to singular.
- *
- * @param bool $singular
- * @return void
- */
- public function singularResourceParameters($singular = true)
- {
- ResourceRegistrar::singularParameters($singular);
- }
-
- /**
- * Set the global resource parameter mapping.
- *
- * @param array $parameters
- * @return void
- */
- public function resourceParameters(array $parameters = [])
- {
- ResourceRegistrar::setParameters($parameters);
- }
-
- /**
- * Get or set the verbs used in the resource URIs.
- *
- * @param array $verbs
- * @return array|null
- */
- public function resourceVerbs(array $verbs = [])
- {
- return ResourceRegistrar::verbs($verbs);
- }
-
/**
* Register an array of resource controllers.
*
@@ -293,29 +256,6 @@ public function resource($name, $controller, array $options = [])
$registrar->register($name, $controller, $options);
}
- /**
- * Register the typical authentication routes for an application.
- *
- * @return void
- */
- public function auth()
- {
- // Authentication Routes...
- $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
- $this->post('login', 'Auth\LoginController@login');
- $this->post('logout', 'Auth\LoginController@logout')->name('logout');
-
- // Registration Routes...
- $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
- $this->post('register', 'Auth\RegisterController@register');
-
- // Password Reset Routes...
- $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
- $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
- $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
- $this->post('password/reset', 'Auth\ResetPasswordController@reset');
- }
-
/**
* Create a route group with shared attributes.
*
@@ -1096,6 +1036,16 @@ public function input($key, $default = null)
return $this->current()->parameter($key, $default);
}
+ /**
+ * Get the request currently being dispatched.
+ *
+ * @return \Illuminate\Http\Request
+ */
+ public function getCurrentRequest()
+ {
+ return $this->currentRequest;
+ }
+
/**
* Get the currently dispatched route instance.
*
@@ -1208,13 +1158,59 @@ public function currentRouteUses($action)
}
/**
- * Get the request currently being dispatched.
+ * Register the typical authentication routes for an application.
*
- * @return \Illuminate\Http\Request
+ * @return void
*/
- public function getCurrentRequest()
+ public function auth()
{
- return $this->currentRequest;
+ // Authentication Routes...
+ $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
+ $this->post('login', 'Auth\LoginController@login');
+ $this->post('logout', 'Auth\LoginController@logout')->name('logout');
+
+ // Registration Routes...
+ $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
+ $this->post('register', 'Auth\RegisterController@register');
+
+ // Password Reset Routes...
+ $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
+ $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
+ $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
+ $this->post('password/reset', 'Auth\ResetPasswordController@reset');
+ }
+
+ /**
+ * Set the unmapped global resource parameters to singular.
+ *
+ * @param bool $singular
+ * @return void
+ */
+ public function singularResourceParameters($singular = true)
+ {
+ ResourceRegistrar::singularParameters($singular);
+ }
+
+ /**
+ * Set the global resource parameter mapping.
+ *
+ * @param array $parameters
+ * @return void
+ */
+ public function resourceParameters(array $parameters = [])
+ {
+ ResourceRegistrar::setParameters($parameters);
+ }
+
+ /**
+ * Get or set the verbs used in the resource URIs.
+ *
+ * @param array $verbs
+ * @return array|null
+ */
+ public function resourceVerbs(array $verbs = [])
+ {
+ return ResourceRegistrar::verbs($verbs);
}
/** | false |
Other | laravel | framework | a7f60ccfde8a06319050873c54f5597e496b8424.json | Apply fixes from StyleCI (#16908) | src/Illuminate/Routing/Route.php | @@ -4,12 +4,9 @@
use Closure;
use LogicException;
-use ReflectionMethod;
use ReflectionFunction;
use Illuminate\Support\Arr;
-use Illuminate\Support\Str;
use Illuminate\Http\Request;
-use UnexpectedValueException;
use Illuminate\Container\Container;
use Illuminate\Routing\Matching\UriValidator;
use Illuminate\Routing\Matching\HostValidator; | false |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | src/Illuminate/Routing/Route.php | @@ -16,7 +16,6 @@
use Illuminate\Routing\Matching\MethodValidator;
use Illuminate\Routing\Matching\SchemeValidator;
use Illuminate\Http\Exception\HttpResponseException;
-use Symfony\Component\Routing\Route as SymfonyRoute;
class Route
{
@@ -27,63 +26,63 @@ class Route
*
* @var string
*/
- protected $uri;
+ public $uri;
/**
* The HTTP methods the route responds to.
*
* @var array
*/
- protected $methods;
+ public $methods;
/**
* The route action array.
*
* @var array
*/
- protected $action;
+ public $action;
/**
* The controller instance.
*
* @var mixed
*/
- protected $controller;
+ public $controller;
/**
* The default values for the route.
*
* @var array
*/
- protected $defaults = [];
+ public $defaults = [];
/**
* The regular expression requirements.
*
* @var array
*/
- protected $wheres = [];
+ public $wheres = [];
/**
* The array of matched parameters.
*
* @var array
*/
- protected $parameters;
+ public $parameters;
/**
* The parameter names for the route.
*
* @var array|null
*/
- protected $parameterNames;
+ public $parameterNames;
/**
* The compiled version of the route.
*
* @var \Symfony\Component\Routing\CompiledRoute
*/
- protected $compiled;
+ public $compiled;
/**
* The router instance used by the route.
@@ -166,13 +165,11 @@ protected function isControllerAction()
*/
protected function runCallable()
{
- $parameters = $this->resolveMethodDependencies(
- $this->parametersWithoutNulls(), new ReflectionFunction($this->action['uses'])
- );
-
$callable = $this->action['uses'];
- return $callable(...array_values($parameters));
+ return $callable(...array_values($this->resolveMethodDependencies(
+ $this->parametersWithoutNulls(), new ReflectionFunction($this->action['uses'])
+ )));
}
/**
@@ -246,101 +243,11 @@ public function matches(Request $request, $includingMethod = true)
*/
protected function compileRoute()
{
- if ($this->compiled) {
- return;
- }
-
- $optionals = $this->extractOptionalParameters();
-
- $uri = preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->uri);
-
- $this->compiled = (
- new SymfonyRoute($uri, $optionals, $this->wheres, [], $this->domain() ?: '')
- )->compile();
- }
-
- /**
- * Get the optional parameters for the route.
- *
- * @return array
- */
- protected function extractOptionalParameters()
- {
- preg_match_all('/\{(\w+?)\?\}/', $this->uri, $matches);
-
- return isset($matches[1]) ? array_fill_keys($matches[1], null) : [];
- }
-
- /**
- * Get all middleware, including the ones from the controller.
- *
- * @return array
- */
- public function gatherMiddleware()
- {
- return array_unique(array_merge($this->middleware(), $this->controllerMiddleware()), SORT_REGULAR);
- }
-
- /**
- * Get or set the middlewares attached to the route.
- *
- * @param array|string|null $middleware
- * @return $this|array
- */
- public function middleware($middleware = null)
- {
- if (is_null($middleware)) {
- return (array) Arr::get($this->action, 'middleware', []);
- }
-
- if (is_string($middleware)) {
- $middleware = func_get_args();
- }
-
- $this->action['middleware'] = array_merge(
- (array) Arr::get($this->action, 'middleware', []), $middleware
- );
-
- return $this;
- }
-
- /**
- * Get the middleware for the route's controller.
- *
- * @return array
- */
- public function controllerMiddleware()
- {
- if (! $this->isControllerAction()) {
- return [];
+ if (! $this->compiled) {
+ $this->compiled = (new RouteCompiler($this))->compile();
}
- return ControllerDispatcher::getMiddleware(
- $this->getController(), $this->getControllerMethod()
- );
- }
-
- /**
- * Get the parameters that are listed in the route / controller signature.
- *
- * @param string|null $subClass
- * @return array
- */
- public function signatureParameters($subClass = null)
- {
- $action = $this->getAction();
-
- if (is_string($action['uses'])) {
- list($class, $method) = explode('@', $action['uses']);
-
- $parameters = (new ReflectionMethod($class, $method))->getParameters();
- } else {
- $parameters = (new ReflectionFunction($action['uses']))->getParameters();
- }
-
- return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
- return $p->getClass() && $p->getClass()->isSubclassOf($subClass);
- });
+ return $this->compiled;
}
/**
@@ -368,18 +275,6 @@ public function hasParameter($name)
return array_key_exists($name, $this->parameters());
}
- /**
- * Get a given parameter from the route.
- *
- * @param string $name
- * @param mixed $default
- * @return string|object
- */
- public function getParameter($name, $default = null)
- {
- return $this->parameter($name, $default);
- }
-
/**
* Get a given parameter from the route.
*
@@ -475,6 +370,29 @@ protected function compileParameterNames()
}, $matches[1]);
}
+ /**
+ * Get the parameters that are listed in the route / controller signature.
+ *
+ * @param string|null $subClass
+ * @return array
+ */
+ public function signatureParameters($subClass = null)
+ {
+ $action = $this->getAction();
+
+ if (is_string($action['uses'])) {
+ list($class, $method) = explode('@', $action['uses']);
+
+ $parameters = (new ReflectionMethod($class, $method))->getParameters();
+ } else {
+ $parameters = (new ReflectionFunction($action['uses']))->getParameters();
+ }
+
+ return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
+ return $p->getClass() && $p->getClass()->isSubclassOf($subClass);
+ });
+ }
+
/**
* Bind the route to a given request for execution.
*
@@ -756,16 +674,6 @@ public function getPath()
return $this->uri();
}
- /**
- * Get the URI associated with the route.
- *
- * @return string
- */
- public function uri()
- {
- return $this->uri;
- }
-
/**
* Get the HTTP verbs the route responds to.
*
@@ -828,11 +736,11 @@ public function domain()
}
/**
- * Get the URI that the route responds to.
+ * Get the URI associated with the route.
*
* @return string
*/
- public function getUri()
+ public function uri()
{
return $this->uri;
}
@@ -949,6 +857,57 @@ public function setAction(array $action)
return $this;
}
+ /**
+ * Get all middleware, including the ones from the controller.
+ *
+ * @return array
+ */
+ public function gatherMiddleware()
+ {
+ return array_unique(array_merge(
+ $this->middleware(), $this->controllerMiddleware()
+ ), SORT_REGULAR);
+ }
+
+ /**
+ * Get or set the middlewares attached to the route.
+ *
+ * @param array|string|null $middleware
+ * @return $this|array
+ */
+ public function middleware($middleware = null)
+ {
+ if (is_null($middleware)) {
+ return (array) Arr::get($this->action, 'middleware', []);
+ }
+
+ if (is_string($middleware)) {
+ $middleware = func_get_args();
+ }
+
+ $this->action['middleware'] = array_merge(
+ (array) Arr::get($this->action, 'middleware', []), $middleware
+ );
+
+ return $this;
+ }
+
+ /**
+ * Get the middleware for the route's controller.
+ *
+ * @return array
+ */
+ public function controllerMiddleware()
+ {
+ if (! $this->isControllerAction()) {
+ return [];
+ }
+
+ return ControllerDispatcher::getMiddleware(
+ $this->getController(), $this->getControllerMethod()
+ );
+ }
+
/**
* Get the compiled version of the route.
* | true |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | src/Illuminate/Routing/RouteCollection.php | @@ -64,7 +64,7 @@ public function add(Route $route)
*/
protected function addToCollections($route)
{
- $domainAndUri = $route->domain().$route->getUri();
+ $domainAndUri = $route->domain().$route->uri();
foreach ($route->methods() as $method) {
$this->routes[$method][$domainAndUri] = $route; | true |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | src/Illuminate/Routing/RouteCompiler.php | @@ -0,0 +1,54 @@
+<?php
+
+namespace Illuminate\Routing;
+
+use Symfony\Component\Routing\Route as SymfonyRoute;
+
+class RouteCompiler
+{
+ /**
+ * The route instance.
+ *
+ * @var \Illuminate\Routing\Route
+ */
+ protected $route;
+
+ /**
+ * Create a new Route compiler instance.
+ *
+ * @param \Illuminate\Routing\Route $route
+ * @return void
+ */
+ public function __construct($route)
+ {
+ $this->route = $route;
+ }
+
+ /**
+ * Compile the route.
+ *
+ * @return \Symfony\Component\Routing\CompiledRoute
+ */
+ public function compile()
+ {
+ $optionals = $this->getOptionalParameters();
+
+ $uri = preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->route->uri());
+
+ return (
+ new SymfonyRoute($uri, $optionals, $this->route->wheres, [], $this->route->domain() ?: '')
+ )->compile();
+ }
+
+ /**
+ * Get the optional parameters for the route.
+ *
+ * @return array
+ */
+ protected function getOptionalParameters()
+ {
+ preg_match_all('/\{(\w+?)\?\}/', $this->route->uri(), $matches);
+
+ return isset($matches[1]) ? array_fill_keys($matches[1], null) : [];
+ }
+} | true |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | src/Illuminate/Routing/Router.php | @@ -821,7 +821,7 @@ public function substituteImplicitBindings($route)
$class = $parameter->getClass();
if (array_key_exists($parameter->name, $parameters) &&
- ! $route->getParameter($parameter->name) instanceof Model) {
+ ! $route->parameter($parameter->name) instanceof Model) {
$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';
$model = $this->container->make($class->name); | true |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | tests/Routing/RouteRegistrarTest.php | @@ -134,7 +134,7 @@ public function testCanRegisterGroupWithPrefix()
$router->get('users', 'UsersController@index');
});
- $this->assertEquals('api/users', $this->getRoute()->getUri());
+ $this->assertEquals('api/users', $this->getRoute()->uri());
}
public function testCanRegisterGroupWithNamePrefix() | true |
Other | laravel | framework | 9d3ff161fd3929f9a106f007ce63fffdd118d490.json | Extract route compiler. | tests/Routing/RoutingRouteTest.php | @@ -917,21 +917,21 @@ public function testResourceRouting()
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foo-bars/{foo_bar}', $routes[0]->getUri());
+ $this->assertEquals('foo-bars/{foo_bar}', $routes[0]->uri());
$router = $this->getRouter();
$router->resource('foo-bar.foo-baz', 'FooController', ['only' => ['show']]);
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foo-bar/{foo_bar}/foo-baz/{foo_baz}', $routes[0]->getUri());
+ $this->assertEquals('foo-bar/{foo_bar}/foo-baz/{foo_baz}', $routes[0]->uri());
$router = $this->getRouter();
$router->resource('foo-bars', 'FooController', ['only' => ['show'], 'as' => 'prefix']);
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foo-bars/{foo_bar}', $routes[0]->getUri());
+ $this->assertEquals('foo-bars/{foo_bar}', $routes[0]->uri());
$this->assertEquals('prefix.foo-bars.show', $routes[0]->getName());
ResourceRegistrar::verbs([
@@ -942,8 +942,8 @@ public function testResourceRouting()
$router->resource('foo', 'FooController');
$routes = $router->getRoutes();
- $this->assertEquals('foo/ajouter', $routes->getByName('foo.create')->getUri());
- $this->assertEquals('foo/{foo}/modifier', $routes->getByName('foo.edit')->getUri());
+ $this->assertEquals('foo/ajouter', $routes->getByName('foo.create')->uri());
+ $this->assertEquals('foo/{foo}/modifier', $routes->getByName('foo.edit')->uri());
}
public function testResourceRoutingParameters()
@@ -956,8 +956,8 @@ public function testResourceRoutingParameters()
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foos/{foo}', $routes[3]->getUri());
- $this->assertEquals('foos/{foo}/bars/{bar}', $routes[10]->getUri());
+ $this->assertEquals('foos/{foo}', $routes[3]->uri());
+ $this->assertEquals('foos/{foo}/bars/{bar}', $routes[10]->uri());
ResourceRegistrar::setParameters(['foos' => 'oof', 'bazs' => 'b']);
@@ -966,7 +966,7 @@ public function testResourceRoutingParameters()
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('bars/{bar}/foos/{oof}/bazs/{b}', $routes[3]->getUri());
+ $this->assertEquals('bars/{bar}/foos/{oof}/bazs/{b}', $routes[3]->uri());
ResourceRegistrar::setParameters();
ResourceRegistrar::singularParameters(false);
@@ -977,15 +977,15 @@ public function testResourceRoutingParameters()
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foos/{foo}', $routes[3]->getUri());
- $this->assertEquals('foos/{foo}/bars/{bar}', $routes[10]->getUri());
+ $this->assertEquals('foos/{foo}', $routes[3]->uri());
+ $this->assertEquals('foos/{foo}/bars/{bar}', $routes[10]->uri());
$router = $this->getRouter();
$router->resource('foos.bars', 'FooController', ['parameters' => ['foos' => 'foo', 'bars' => 'bar']]);
$routes = $router->getRoutes();
$routes = $routes->getRoutes();
- $this->assertEquals('foos/{foo}/bars/{bar}', $routes[3]->getUri());
+ $this->assertEquals('foos/{foo}/bars/{bar}', $routes[3]->uri());
}
public function testResourceRouteNaming()
@@ -1074,7 +1074,7 @@ public function testRouterFiresRoutedEvent()
unset($_SERVER['__router.request']);
$this->assertInstanceOf('Illuminate\Routing\Route', $_SERVER['__router.route']);
- $this->assertEquals($_SERVER['__router.route']->getUri(), $route->getUri());
+ $this->assertEquals($_SERVER['__router.route']->uri(), $route->uri());
unset($_SERVER['__router.route']);
}
| true |
Other | laravel | framework | 7573abf0202cac49aa626d2186091f45097fff17.json | fix routing pipeline | src/Illuminate/Pipeline/Pipeline.php | @@ -95,17 +95,26 @@ public function via($method)
*/
public function then(Closure $destination)
{
- $destination = function ($passable) use ($destination) {
- return $destination($passable);
- };
-
$pipeline = array_reduce(
- array_reverse($this->pipes), $this->carry(), $destination
+ array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)
);
return $pipeline($this->passable);
}
+ /**
+ * Get the final piece of the Closure onion.
+ *
+ * @param \Closure $destination
+ * @return \Closure
+ */
+ protected function prepareDestination(Closure $destination)
+ {
+ return function ($passable) use ($destination) {
+ return $destination($passable);
+ };
+ }
+
/**
* Get a Closure that represents a slice of the application onion.
* | true |
Other | laravel | framework | 7573abf0202cac49aa626d2186091f45097fff17.json | fix routing pipeline | src/Illuminate/Routing/Pipeline.php | @@ -17,17 +17,37 @@
*/
class Pipeline extends BasePipeline
{
+ /**
+ * Get the final piece of the Closure onion.
+ *
+ * @param \Closure $destination
+ * @return \Closure
+ */
+ protected function prepareDestination(Closure $destination)
+ {
+ return function ($passable) use ($destination) {
+ try {
+ return $destination($passable);
+ } catch (Exception $e) {
+ return $this->handleException($passable, $e);
+ } catch (Throwable $e) {
+ return $this->handleException($passable, new FatalThrowableError($e));
+ }
+ };
+ }
+
/**
* Get a Closure that represents a slice of the application onion.
*
* @return \Closure
*/
- protected function getSlice()
+ protected function carry()
{
return function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
try {
- $slice = parent::getSlice();
+ $slice = parent::carry();
+
$callable = $slice($stack, $pipe);
return $callable($passable);
@@ -40,25 +60,6 @@ protected function getSlice()
};
}
- /**
- * Get the initial slice to begin the stack call.
- *
- * @param \Closure $destination
- * @return \Closure
- */
- protected function getInitialSlice(Closure $destination)
- {
- return function ($passable) use ($destination) {
- try {
- return $destination($passable);
- } catch (Exception $e) {
- return $this->handleException($passable, $e);
- } catch (Throwable $e) {
- return $this->handleException($passable, new FatalThrowableError($e));
- }
- };
- }
-
/**
* Handle the given exception.
* | true |
Other | laravel | framework | 8affc08341beffc81deb3ad78042dcf2dc173027.json | Apply fixes from StyleCI (#16905) | src/Illuminate/Redis/RedisManager.php | @@ -83,8 +83,7 @@ protected function resolve($name)
*/
protected function connector()
{
- switch ($this->driver)
- {
+ switch ($this->driver) {
case 'predis':
return new Connectors\PredisConnector;
case 'phpredis': | false |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php | @@ -4,15 +4,15 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
-use Illuminate\Contracts\Redis\Database as RedisDatabase;
+use Illuminate\Contracts\Redis\Factory as Redis;
use Symfony\Component\HttpKernel\Exception\HttpException;
class RedisBroadcaster extends Broadcaster
{
/**
* The Redis instance.
*
- * @var \Illuminate\Contracts\Redis\Database
+ * @var \Illuminate\Contracts\Redis\Factory
*/
protected $redis;
@@ -26,11 +26,11 @@ class RedisBroadcaster extends Broadcaster
/**
* Create a new broadcaster instance.
*
- * @param \Illuminate\Contracts\Redis\Database $redis
+ * @param \Illuminate\Contracts\Redis\Factory $redis
* @param string $connection
* @return void
*/
- public function __construct(RedisDatabase $redis, $connection = null)
+ public function __construct(Redis $redis, $connection = null)
{
$this->redis = $redis;
$this->connection = $connection; | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Cache/RedisStore.php | @@ -3,14 +3,14 @@
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\Store;
-use Illuminate\Contracts\Redis\Database;
+use Illuminate\Contracts\Redis\Factory as Redis;
class RedisStore extends TaggableStore implements Store
{
/**
- * The Redis database connection.
+ * The Redis factory implementation.
*
- * @var \Illuminate\Contracts\Redis\Database
+ * @var \Illuminate\Contracts\Redis\Factory
*/
protected $redis;
@@ -31,12 +31,12 @@ class RedisStore extends TaggableStore implements Store
/**
* Create a new Redis store.
*
- * @param \Illuminate\Contracts\Redis\Database $redis
+ * @param \Illuminate\Contracts\Redis\Factory $redis
* @param string $prefix
* @param string $connection
* @return void
*/
- public function __construct(Database $redis, $prefix = '', $connection = 'default')
+ public function __construct(Redis $redis, $prefix = '', $connection = 'default')
{
$this->redis = $redis;
$this->setPrefix($prefix); | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Contracts/Redis/Database.php | @@ -1,15 +0,0 @@
-<?php
-
-namespace Illuminate\Contracts\Redis;
-
-interface Database
-{
- /**
- * Run a command against the Redis database.
- *
- * @param string $method
- * @param array $parameters
- * @return mixed
- */
- public function command($method, array $parameters = []);
-} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Contracts/Redis/Factory.php | @@ -0,0 +1,14 @@
+<?php
+
+namespace Illuminate\Contracts\Redis;
+
+interface Factory
+{
+ /**
+ * Get a Redis connection by name.
+ *
+ * @param string $name
+ * @return \Illuminate\Redis\Connections\Connection
+ */
+ public function connection($name = null);
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Foundation/Application.php | @@ -1090,7 +1090,7 @@ public function registerCoreContainerAliases()
'queue.connection' => ['Illuminate\Contracts\Queue\Queue'],
'queue.failer' => ['Illuminate\Queue\Failed\FailedJobProviderInterface'],
'redirect' => ['Illuminate\Routing\Redirector'],
- 'redis' => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],
+ 'redis' => ['Illuminate\Redis\RedisManager', 'Illuminate\Contracts\Redis\Factory'],
'request' => ['Illuminate\Http\Request', 'Symfony\Component\HttpFoundation\Request'],
'router' => ['Illuminate\Routing\Router', 'Illuminate\Contracts\Routing\Registrar', 'Illuminate\Contracts\Routing\BindingRegistrar'],
'session' => ['Illuminate\Session\SessionManager'], | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Queue/Connectors/RedisConnector.php | @@ -4,14 +4,14 @@
use Illuminate\Support\Arr;
use Illuminate\Queue\RedisQueue;
-use Illuminate\Contracts\Redis\Database;
+use Illuminate\Contracts\Redis\Factory as Redis;
class RedisConnector implements ConnectorInterface
{
/**
* The Redis database instance.
*
- * @var \Illuminate\Contracts\Redis\Database
+ * @var \Illuminate\Contracts\Redis\Factory
*/
protected $redis;
@@ -25,11 +25,11 @@ class RedisConnector implements ConnectorInterface
/**
* Create a new Redis queue connector instance.
*
- * @param \Illuminate\Contracts\Redis\Database $redis
+ * @param \Illuminate\Contracts\Redis\Factory $redis
* @param string|null $connection
* @return void
*/
- public function __construct(Database $redis, $connection = null)
+ public function __construct(Redis $redis, $connection = null)
{
$this->redis = $redis;
$this->connection = $connection; | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Queue/Jobs/RedisJob.php | @@ -112,9 +112,9 @@ public function getJobId()
}
/**
- * Get the underlying queue driver instance.
+ * Get the underlying Redis factory implementation.
*
- * @return \Illuminate\Contracts\Redis\Database
+ * @return \Illuminate\Contracts\Redis\Factory
*/
public function getRedisQueue()
{ | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Queue/RedisQueue.php | @@ -5,15 +5,15 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Queue\Jobs\RedisJob;
-use Illuminate\Contracts\Redis\Database;
+use Illuminate\Contracts\Redis\Factory as Redis;
use Illuminate\Contracts\Queue\Queue as QueueContract;
class RedisQueue extends Queue implements QueueContract
{
/**
- * The Redis database instance.
+ * The Redis factory implementation.
*
- * @var \Illuminate\Contracts\Redis\Database
+ * @var \Illuminate\Contracts\Redis\Factory
*/
protected $redis;
@@ -41,14 +41,13 @@ class RedisQueue extends Queue implements QueueContract
/**
* Create a new Redis queue instance.
*
- * @param \Illuminate\Contracts\Redis\Database $redis
+ * @param \Illuminate\Contracts\Redis\Factory $redis
* @param string $default
* @param string $connection
* @param int $expire
* @return void
*/
- public function __construct(Database $redis, $default = 'default',
- $connection = null, $expire = 60)
+ public function __construct(Redis $redis, $default = 'default', $connection = null, $expire = 60)
{
$this->redis = $redis;
$this->expire = $expire; | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connections/Connection.php | @@ -0,0 +1,84 @@
+<?php
+
+namespace Illuminate\Redis\Connections;
+
+use Closure;
+
+abstract class Connection
+{
+ /**
+ * The Predis client.
+ *
+ * @var \Predis\Client
+ */
+ protected $client;
+
+ /**
+ * Subscribe to a set of given channels for messages.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @param string $method
+ * @return void
+ */
+ abstract public function createSubscription($channels, Closure $callback, $method = 'subscribe');
+
+ /**
+ * Get the underlying Redis client.
+ *
+ * @return mixed
+ */
+ public function client()
+ {
+ return $this->client;
+ }
+
+ /**
+ * Subscribe to a set of given channels for messages.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @param string $method
+ * @return void
+ */
+ public function subscribe($channels, Closure $callback)
+ {
+ return $this->createSubscription($channels, $callback, __FUNCTION__);
+ }
+
+ /**
+ * Subscribe to a set of given channels with wildcards.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @return void
+ */
+ public function psubscribe($channels, Closure $callback)
+ {
+ return $this->createSubscription($channels, $callback, __FUNCTION__);
+ }
+
+ /**
+ * Run a command against the Redis database.
+ *
+ * @param string $method
+ * @param array $parameters
+ * @return mixed
+ */
+ public function command($method, array $parameters = [])
+ {
+ return $this->client->{$method}(...$parameters);
+ }
+
+ /**
+ * Pass other method calls down to the underlying client.
+ *
+ * @param string $method
+ * @param array $parameters
+ * @return mixed
+ */
+ public function __call($method, $parameters)
+ {
+ return $this->command($method, $parameters);
+ }
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connections/PhpRedisClusterConnection.php | @@ -0,0 +1,8 @@
+<?php
+
+namespace Illuminate\Redis\Connections;
+
+class PhpRedisClusterConnection extends PhpRedisConnection
+{
+ //
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connections/PhpRedisConnection.php | @@ -0,0 +1,73 @@
+<?php
+
+namespace Illuminate\Redis\Connections;
+
+use Closure;
+
+class PhpRedisConnection extends Connection
+{
+ /**
+ * Create a new Predis connection.
+ *
+ * @param \Predis\Client $client
+ * @return void
+ */
+ public function __construct($client)
+ {
+ $this->client = $client;
+ }
+
+ /**
+ * Evaluate a Lua script and return the result.
+ *
+ * @param string $script
+ * @param int $numberOfKeys
+ * @param dynamic $arguments
+ * @return mixed
+ */
+ public function eval($script, $numberOfKeys, ...$arguments)
+ {
+ return $this->client->eval($script, $arguments, $numberOfKeys);
+ }
+
+ /**
+ * Subscribe to a set of given channels for messages.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @return void
+ */
+ public function subscribe($channels, Closure $callback)
+ {
+ $this->client->subscribe((array) $channels, function ($redis, $channel, $message) use ($callback) {
+ $callback($message, $channel);
+ });
+ }
+
+ /**
+ * Subscribe to a set of given channels with wildcards.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @return void
+ */
+ public function psubscribe($channels, Closure $callback)
+ {
+ $this->client->psubscribe((array) $channels, function ($redis, $pattern, $channel, $message) use ($callback) {
+ $callback($message, $channel);
+ });
+ }
+
+ /**
+ * Subscribe to a set of given channels for messages.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @param string $method
+ * @return void
+ */
+ public function createSubscription($channels, Closure $callback, $method = 'subscribe')
+ {
+ //
+ }
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connections/PredisClusterConnection.php | @@ -0,0 +1,8 @@
+<?php
+
+namespace Illuminate\Redis\Connections;
+
+class PredisClusterConnection extends PredisConnection
+{
+ //
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connections/PredisConnection.php | @@ -0,0 +1,42 @@
+<?php
+
+namespace Illuminate\Redis\Connections;
+
+use Closure;
+
+class PredisConnection extends Connection
+{
+ /**
+ * Create a new Predis connection.
+ *
+ * @param \Predis\Client $client
+ * @return void
+ */
+ public function __construct($client)
+ {
+ $this->client = $client;
+ }
+
+ /**
+ * Subscribe to a set of given channels for messages.
+ *
+ * @param array|string $channels
+ * @param \Closure $callback
+ * @param string $method
+ * @return void
+ */
+ public function createSubscription($channels, Closure $callback, $method = 'subscribe')
+ {
+ $loop = $this->pubSubLoop();
+
+ call_user_func_array([$loop, $method], (array) $channels);
+
+ foreach ($loop as $message) {
+ if ($message->kind === 'message' || $message->kind === 'pmessage') {
+ call_user_func($callback, $message->payload, $message->channel);
+ }
+ }
+
+ unset($loop);
+ }
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connectors/PhpRedisConnector.php | @@ -0,0 +1,118 @@
+<?php
+
+namespace Illuminate\Redis\Connectors;
+
+use Redis;
+use RedisCluster;
+use Illuminate\Support\Arr;
+use Illuminate\Redis\Connections\PhpRedisConnection;
+use Illuminate\Redis\Connections\PhpRedisClusterConnection;
+
+class PhpRedisConnector
+{
+ /**
+ * Create a new clustered Predis connection.
+ *
+ * @param array $config
+ * @param array $clusterOptions
+ * @param array $options
+ * @return \Illuminate\Redis\PredisConnection
+ */
+ public function connect(array $config, array $options)
+ {
+ return new PhpRedisConnection($this->createClient(array_merge(
+ $config, $options, Arr::pull($config, 'options', [])
+ )));
+ }
+
+ /**
+ * Create a new clustered Predis connection.
+ *
+ * @param array $config
+ * @param array $clusterOptions
+ * @param array $options
+ * @return \Illuminate\Redis\PredisClusterConnection
+ */
+ public function connectToCluster(array $config, array $clusterOptions, array $options)
+ {
+ $options = array_merge($options, $clusterOptions, Arr::pull($config, 'options', []));
+
+ return new PhpRedisClusterConnection($this->createRedisClusterInstance(
+ array_map([$this, 'buildClusterConnectionString'], $config), $options
+ ));
+ }
+
+ /**
+ * Build a single cluster seed string from array.
+ *
+ * @param array $server
+ * @return string
+ */
+ protected function buildClusterConnectionString(array $server)
+ {
+ return $server['host'].':'.$server['port'].'?'.http_build_query(Arr::only($server, [
+ 'database', 'password', 'prefix', 'read_timeout',
+ ]));
+ }
+
+ /**
+ * Create the Redis client instance.
+ *
+ * @param array $config
+ * @return \Redis
+ */
+ protected function createClient(array $config)
+ {
+ return tap(new Redis, function ($client) use ($config) {
+ $this->establishConnection($client, $config);
+
+ if (! empty($config['password'])) {
+ $client->auth($config['password']);
+ }
+
+ if (! empty($config['database'])) {
+ $client->select($config['database']);
+ }
+
+ if (! empty($config['prefix'])) {
+ $client->setOption(Redis::OPT_PREFIX, $config['prefix']);
+ }
+
+ if (! empty($config['read_timeout'])) {
+ $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
+ }
+ });
+ }
+
+ /**
+ * Establish a connection with the Redis host.
+ *
+ * @param \Redis $client
+ * @param array $config
+ * @return void
+ */
+ protected function establishConnection($client, array $config)
+ {
+ $client->{Arr::get($config, 'persistent', false) === true ? 'pconnect' : 'connect'}(
+ $config['host'], $config['port'], Arr::get($config, 'timeout', 0)
+ );
+ }
+
+ /**
+ * Create a new redis cluster instance.
+ *
+ * @param array $servers
+ * @param array $options
+ * @return \RedisCluster
+ */
+ protected function createRedisClusterInstance(array $servers, array $options)
+ {
+ return new RedisCluster(
+ null,
+ array_values($servers),
+ Arr::get($options, 'timeout', 0),
+ Arr::get($options, 'read_timeout', 0),
+ isset($options['persistent']) && $options['persistent']
+ );
+ }
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Connectors/PredisConnector.php | @@ -0,0 +1,41 @@
+<?php
+
+namespace Illuminate\Redis\Connectors;
+
+use Predis\Client;
+use Illuminate\Support\Arr;
+use Illuminate\Redis\Connections\PredisConnection;
+use Illuminate\Redis\Connections\PredisClusterConnection;
+
+class PredisConnector
+{
+ /**
+ * Create a new clustered Predis connection.
+ *
+ * @param array $config
+ * @param array $clusterOptions
+ * @param array $options
+ * @return \Illuminate\Redis\PredisConnection
+ */
+ public function connect(array $config, array $options)
+ {
+ return new PredisConnection(new Client($config, array_merge(
+ ['timeout' => 10.0], $options, Arr::pull($config, 'options', [])
+ )));
+ }
+
+ /**
+ * Create a new clustered Predis connection.
+ *
+ * @param array $config
+ * @param array $clusterOptions
+ * @param array $options
+ * @return \Illuminate\Redis\PredisClusterConnection
+ */
+ public function connectToCluster(array $config, array $clusterOptions, array $options)
+ {
+ return new PredisClusterConnection(new Client(array_values($config), array_merge(
+ $options, $clusterOptions, Arr::pull($config, 'options', [])
+ )));
+ }
+} | true |
Other | laravel | framework | 1ef8b9c3f156c7d4debc6c6f67b73b032d8337d5.json | Rewrite Redis layer.
This rewrite the Redis layer to function more like database or cache
drivers… a new Redis factory is introduced to retrieve Redis connection
instances. Different Redis connection instances are introduced to
account for differences between the two drivers (Predis and PhpRedis). | src/Illuminate/Redis/Database.php | @@ -1,44 +0,0 @@
-<?php
-
-namespace Illuminate\Redis;
-
-use Illuminate\Support\Arr;
-use Illuminate\Contracts\Redis\Database as DatabaseContract;
-
-abstract class Database implements DatabaseContract
-{
- /**
- * Get a specific Redis connection instance.
- *
- * @param string $name
- * @return \Predis\ClientInterface|\RedisCluster|\Redis|null
- */
- public function connection($name = 'default')
- {
- return Arr::get($this->clients, $name ?: 'default');
- }
-
- /**
- * Run a command against the Redis database.
- *
- * @param string $method
- * @param array $parameters
- * @return mixed
- */
- public function command($method, array $parameters = [])
- {
- return call_user_func_array([$this->clients['default'], $method], $parameters);
- }
-
- /**
- * Dynamically make a Redis command.
- *
- * @param string $method
- * @param array $parameters
- * @return mixed
- */
- public function __call($method, $parameters)
- {
- return $this->command($method, $parameters);
- }
-} | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.